SQL查询,用于查找至少包含一个列出的标记的文章

时间:2010-02-10 22:45:31

标签: sql select mysql

我有3个表:文章,标签和article_tag(连接它们的那个)。

我想查找查询中列出的一些(或全部)标记的所有文章,并按匹配标记的数量排序。有可能吗?

英语示例:

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)

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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