Skip to content
Advertisement

return number of hashtag posts sql, mysql

I have two tables, 1) hashtags table & 2) hashtags_relation table.

The first one lists the hashtags, and the second one relates the hashtag with a post.

TABLE HASHTAGS

 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

EXPECTED OUTPUT

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

SQL QUERY (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

PROBLEM

How do I get, the number of posts of each hashtag? I tried using ht.count(*)

Advertisement

Answer

You need to use 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;
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement