什么是热门标签的查询? 的 Tabels
blog_tags
id name
1 tag1
2 tag2
3 tag3
4 tag4
5 tag5
blog_post_tags
id post_id blog_tag_id
1 1 2
2 2 2
3 1 3
4 3 5
5 4 2
output
tag2
tag3
tag5
我开始写这样的查询:
SELECT bt.id, bt.name, bpt.blog_tag_id
FROM
blog_tags bt
RIGHT JOIN
blog_post_tags bpt
ON
bt.id = bpt.blog_tag_id
ORDER BY bt.name ASC
它给出了blog_post_tags中使用的标签的输出,但我希望标签根据受欢迎程度进行排序。
答案 0 :(得分:2)
SELECT blog_tags.name, t.used_cnt FROM blog_tags
INNER JOIN (
SELECT blog_tag_id, count(*) as used_cnt
from blog_post_tags
group by blog_tag_id
)t
ON blog_tags.id = t.blog_tag_id
ORDER BY t.used_cnt DESC
答案 1 :(得分:2)
只需将right join
替换为inner join
,将group by
代码ID替换为:
select bt.name
from blog_post_tags bpt
join blog_tags bt on bpt.blog_tag_id = bt.id
group by bt.id, bt.name -- Edit: fixing for some strict dbs
order by count(bpt.post_id) desc
请参阅sqlfiddle中的demo。
答案 2 :(得分:1)
我认为这样的查询应该有效:
select name from (select blog_tag_id,count(*) as cnt from blog_post_tags group by blog_tag_id order by cnt dsc ) as a inner join blog_tags on a.blog_tag_id = blog_tags.id