簡體   English   中英

SQL查詢以查找具有至少一個列出標簽的文章

[英]SQL-query to find articles with at least one of the listed tags

我有3個表:articles,tags和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)

大概是這樣的:

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
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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM