2010-02-10 66 views
0

我有3個表:文章,標籤和article_tag(連接它們的那個)。查詢至少有一個列出的標籤的SQL查詢

我想查找所有包含查詢中列出的一些(或全部)標籤的文章,並按匹配標籤的數量排列。可能嗎?

實例中英文:

Query: Find me all articles that have at least one of these tags "jazz, bass guitar, soul, funk", order them by the number of matched tags. 

Output: 
Article 1 (jazz, bass-guitar, soul, funk) 
Article 2 (jazz, bass-guitar, soul) 
Article 3 (jazz, bass-guitar) 
Article 4 (funk) 

回答

3

大概是這樣的:

select articles.article_id, count(tags.tag_id) as num_tags, group_concat(distinct tag_name separator ',') as tags 
from articles, article_tag, tags 
where articles.tag_id = article_tag.tag_id 
    and article_tag.tag_id = tags.tag_id 
    and tags.tag_name in ('jazz', 'funk', 'soul', 'Britney Spears') 
group by articles.article_id 
order by count(tags.tag_id) desc 
+0

GROUP_CONCAT()。但實際上,DISTINCT不應該是必需的 - 模式應該已經實施了獨特的文章/標籤組合。我要添加的是一個ORDER BY tag_name,所以這個列表可以用alfabetically整齊排序。 – 2010-02-10 23:20:54

+0

是的,架構沒有發佈,所以我不知道它會執行什麼。 – Corey 2010-02-10 23:29:41

+3

謝謝。你犯了一個小錯誤,articles.tag_id應該是WHERE子句中的articles.article_id。但是非常感謝。 – snitko 2010-02-10 23:46:00

1
select a.* from articles a, 
(select article_id, count(*) cnt from article_tag at, tag t 
    where t.name in ('jazz', 'bass-guitar', 'soul', 'funk') 
    and at.tag_id = t.tag_id 
    group by article_id) art_tag 
where a.article_id = art_tag.article_id 
order by art_tag.cnt desc 
+0

不會被匹配標籤的編號順序。 – Corey 2010-02-10 22:52:53

+0

對不起,錯過了第一個讀過的部分... – 2010-02-10 22:56:19