返回主题标签的数量sql,mysql

时间:2018-09-01 15:28:58

标签: mysql sql

我有两个表,1)hashtags表和2)hashtags_relation表。

第一个列出主题标签,第二个列出主题标签与帖子。

表标签

 id_hashtag | hashtag | 
  3         #love
  4         #monday
  5         #yesterday

**TABLE HASHTAGS RELATIONS**


id_hashtag | id_post | 
3           1234
3           1235
3           1236
4           1541
4           1543
5           1720
5           1721
5           1722
5           1723
5           1724

预期输出

 #yesterday - 5 posts
 #love - 3 posts
 #monday - 2 posts

SQL查询(MYSQL)

SELECT hs.*, ht.count(*) as count ?
FROM hashtags hs
LEFT JOIN hashtag_relation hr ON hs.id_hashtag=hr.id_hashtag
WHERE 1 
ORDER BY (ht.number of posts?) 
DESC 
LIMIT 10

问题

如何获取每个主题标签的帖子数量?我尝试使用ht.count(*)

1 个答案:

答案 0 :(得分:1)

您需要使用GROUP BY

SELECT hs.hashtag, count(hr.id_hashtag) as cnt
FROM hashtags hs
LEFT JOIN hashtag_relation hr ON hs.id_hashtag=hr.id_hashtag
GROUP BY hs.hashtag
ORDER BY cnt DESC LIMIT 10;