我的SQL查询包含posts表,post_likes表和comments表的三个表。 所有表都与posts表中的post_id主键相关联。我试图返回帖子行的内容以及它在post_likes表中的喜欢/不喜欢的数量,以及评论的数量。查询工作正常,直到我引入了第二个左连接,它现在显示了like_count列x5 dislike_count列x5和新的comment_count x4。
这是有问题的查询:
SELECT c.post_id, c.post_name, c.post_content, c.post_datetime, c.user_name, sum(p.like_count) AS like_count, sum(p.dislike_count) AS dislike_count, sum(s.comment_count) AS comment_count FROM posts c LEFT JOIN post_likes p ON c.post_id = p.post_id LEFT JOIN comments s ON c.post_id = s.post_id WHERE c.user_name = 'test' GROUP BY c.post_id
返回总和值:
//column | returned value | expected value
like_count | 10 | 2
dislike_count | 5 | 1
comment_count | 20 | 5
一些额外的注释,喜欢/不喜欢的内容存储在带有结构的postlikes表中。
post_like_id, like_count, dislike_count, post_id, user_name
在PHP处理此列的任一列中,喜欢或不喜欢的计数只能为1,以确保用户不能多次等,而user_name列是喜欢该帖子的用户。
评论表结构如下:
comment_id, comment_name, comment_content, comment_datetime, comment_count, post_id, user_name
插入时,comment_count始终为1以允许sum函数,post_id是注释的帖子的id,而user_name是评论的用户。
答案 0 :(得分:1)
您的joins
正在生成笛卡尔积 - 而是将聚合结果移到子查询中:
SELECT c.post_id, c.post_name, c.post_content, c.post_datetime, c.user_name,
p.like_count,
p.dislike_count,
s.comment_count
FROM posts c
LEFT JOIN (
select post_id,
sum(like_count) like_count,
sum(dislike_count) dislike_count
from post_likes
group by post_id
) p ON c.post_id = p.post_id
LEFT JOIN (
select post_id, sum(comment_count) comment_count
from comments
group by post_id
) s ON c.post_id = s.post_id
WHERE c.user_name = 'test'