Ivan
Ivan

Reputation: 5238

MySQL count likes and dislikes

Guys i want to merge two tables. First table is comments and second table is likes. Likes contain likes and dislikes col rate (1 = liked, 2 = disliked)

So i want when i show all comments also i want to add two new cols likes and dislikes where i count how much likes and dislikes has one comment. I do that just for likes but i dont know how to do also for dislikes.

SO here is like table where i save likes:

like_id  item_id  account_id    rate  time                 host    
-------  -------  ----------  ------  -------------------  --------
    308      262           1       1  2016-03-18 13:45:16  (NULL)  
    309      263           1       2  2016-03-18 13:45:33  (NULL)  
    310      262           7       2  2016-03-18 14:23:49  (NULL)  
    311      262           8       1  2016-03-18 14:24:11  (NULL)  

And here is comment table:

comment_id  item_id   content       account_id     time                 
-------     -------  ----------     ------------  -------------------
  308       262      Test comment      1          2016-03-18 13:45:16  

So i want to do this result

comment_id  item_id   content    account_id     time    Likes  Dislike         
-------     -------  ---------    ------------  -----  -------- ------
 1           267      test comm        1                 4        2

My query

SELECT c.comment_id, acc.account_id, acc.account_firstname, acc.account_lastname,p.photo_name,p.photo_guid, COUNT(_like.item_id) AS likes
FROM pb_account_comments AS c
INNER JOIN pb_accounts AS acc ON acc.account_id = c.account_id
LEFT JOIN pb_account_photos AS p ON p.photo_id = acc.profile_picture_id
LEFT JOIN pb_account_likes AS _like ON _like.item_id = c.comment_id 
WHERE c.item_id = '2' GROUP BY c.comment_id
ORDER BY posted_date ASC LIMIT 0,3;

My query just count likes and this work good but how can i count and dislikes?

Upvotes: 3

Views: 2173

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1271211

I'm not sure what the extra columns are needed for. Normally, such columns should also be included in the GROUP BY.

A simpler version of your query just returns the information for each comment using conditional aggregation:

SELECT c.comment_id,
       COALESCE(SUM(l.rate = 1), 0) AS likes,
       COALESCE(SUM(l.rate = 2), 0) AS dislikes
FROM pb_account_comments c INNER JOIN
     pb_account_likes l
    ON l.item_id = c.comment_id 
WHERE c.item_id = 2
GROUP BY c.comment_id
ORDER BY posted_date ASC 
LIMIT 0, 3;

Upvotes: 4

Related Questions