我有三个表格-点赞,评论和帖子。点赞和评论表具有引用帖子的ID。
我希望能够对帖子的喜欢和评论进行计数,但是,我对子查询的有限了解确实证明是一项艰巨的任务,并且没有大量的研究提供答案。
我的表布局有一个SQL Fiddle;我一直在脑子里打乱我的书桌上好几个小时,而且还差一点!!
注释
喜欢
帖子
最佳答案
您可以使用join
获得所需的结果,例如:
SELECT p.post_id, COUNT(l.like_id) AS likes, COUNT(c.comment_id) AS comments
FROM posts p LEFT JOIN likes l ON p.post_id = l.like_post
LEFT JOIN comments c ON p.post_id = c.comment_post
GROUP BY p.post_id;
我们在这里使用了
LEFT JOIN
,这意味着即使没有任何喜欢或评论,也会显示帖子表中的所有记录。下面是获得相同输出的子查询方式:
SELECT post_id,
(SELECT COUNT(*) FROM likes WHERE like_post = post_id) AS likes,
(SELECT COUNT(*) FROM comments where comment_post = post_id) AS comments
FROM posts;
更新资料
如果要计算总数,则可以在查询中使用变量,例如:
SELECT post_id,
@comments := (SELECT COUNT(*) FROM likes WHERE like_post = post_id) AS likes,
@likes := (SELECT COUNT(*) FROM comments where comment_post = post_id) AS comments,
(@comments + @likes) as total
FROM posts, (SELECT @comments:=0, @likes := 0) a;
关于mysql - MySQL-正确的人口,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42307676/