伙计们,我想合并两个表。第一个表是comments
,第二个表是likes
。喜欢包含喜欢和不喜欢的列 rate
(1 = 喜欢,2 = 不喜欢)
所以我想当我显示所有评论时我也想添加两个新的列喜欢
和不喜欢
,其中我计算一条评论有多少喜欢和不喜欢。我这样做只是为了喜欢,但我不知道如何为不喜欢做。
这里就像我保存喜欢的表格:
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;
我的查询只计算喜欢的数量,这很好用,但是我如何计算喜欢和不喜欢的数量?
最佳答案
我不确定需要额外的列做什么。通常,此类列也应包含在 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;
关于MySQL统计喜欢和不喜欢的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36449841/