2010-02-10 71 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