MySQL数量喜欢和不喜欢

时间:2016-04-06 11:30:47

标签: mysql sql

伙计们我想合并两张桌子。第一个表是comments,第二个表是likes。喜欢包含喜欢和不喜欢col rate(1 =喜欢,2 =不喜欢)

所以,当我显示所有评论时,我想要添加两个新的cols likesdislikes,其中我计算有多少喜欢和不喜欢的评论。我这样做只是为了喜欢,但我也不知道怎么做也不喜欢。

所以这就像我保存喜欢的表:

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)  

这是评论表:

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

所以我想做这个结果

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

我的查询

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;

我的查询只计算喜欢,这项工作很好,但我怎么能算和不喜欢?

1 个答案:

答案 0 :(得分:1)

我不确定需要多少列。通常,此类列也应包含在GROUP BY

更简单的查询版本只使用条件聚合返回每条评论的信息:

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;