使用左连接计算多个表中的关联行

时间:2014-06-24 11:32:07

标签: mysql sql

我正在尝试使用PostsComments的关联号码选择Likes

这是我的查询

SELECT `waller_posts`.*,
       COUNT(waller_comments.id) AS num_comments,
       COUNT(waller_likes.id) AS num_likes
FROM `waller_posts`
LEFT JOIN `waller_comments` ON `waller_comments`.`post_id` = `waller_posts`.`id`
LEFT JOIN `waller_likes` ON `waller_likes`.`post_id` = `waller_posts`.`id`
WHERE `wall_id` = 1
  AND `wall_type` = "User"
GROUP BY `waller_posts`.`id`

当我在left join的这种情况下添加第二个likes时,num_commentsnum_likes的结果出错了。我该如何进行这种查询?

2 个答案:

答案 0 :(得分:1)

该查询构建为在帖子上为您提供评论和喜欢的所有可能组合。

可能最容易使用COUNT(DISTINCT ...): -

SELECT `waller_posts`.*,
       COUNT(DISTINCT waller_comments.id) AS num_comments,
       COUNT(DISTINCT waller_likes.id) AS num_likes
FROM `waller_posts`
LEFT JOIN `waller_comments` ON `waller_comments`.`post_id` = `waller_posts`.`id`
LEFT JOIN `waller_likes` ON `waller_likes`.`post_id` = `waller_posts`.`id`
WHERE `wall_id` = 1
  AND `wall_type` = "User"
GROUP BY `waller_posts`.`id`

请注意,您的查询依赖于MySQL的功能,但这会导致大多数SQL的错误。对于大多数SQL,您需要在GROUP BY子句中列出所有非聚合列。

答案 1 :(得分:0)

使用Distinct子句,因为它将显示like和comment表数据的组合

SELECT `waller_posts`.*,
       COUNT(DISTINCT waller_comments.id) AS num_comments,
       COUNT(DISTINCT waller_likes.id) AS num_likes
FROM `waller_posts`
LEFT JOIN `waller_comments` ON `waller_comments`.`post_id` = `waller_posts`.`id`
LEFT JOIN `waller_likes` ON `waller_likes`.`post_id` = `waller_posts`.`id`
WHERE `wall_id` = 1
  AND `wall_type` = "User"
GROUP BY `waller_posts`.`id`