MySQL - 正确的人口

时间:2017-02-17 21:27:01

标签: mysql join

我有三张桌子 - 喜欢,评论和帖子。喜欢和评论表具有引用帖子的ID。

我希望能够计算帖子上的喜欢和评论,但是,我对子查询的有限知识确实是一项艰巨的任务,没有多少研究可以提供答案。

我有SQL Fiddle表格的布局;我已经在我的桌子上打了几个小时,仍然没有一个字节更接近!!

评论

Comment table

喜欢

Like table

帖子

Posts table

2 个答案:

答案 0 :(得分:1)

我会将GROUP BY用于此

SELECT 
posts.post_id, COUNT(DISTINCT likes.like_id) as likes,COUNT(DISTINCT comments.comment_id) as comments,
FROM posts
LEFT JOIN likes ON likes.like_post=posts.post_id
LEFT JOIN comments ON comments.comment_post=posts.id
GROUP BY posts.post_id

当您加入两个以上的表时,您必须将DISTINCT添加到COUNT,否则您会将评论的数量乘以喜欢的数量,反之亦然

答案 1 :(得分:0)

您可以使用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;