简体   繁体   中英

count associate rows in multiple tables with left join

I'm trying to select Posts with the associate numbers of Comments and Likes .

This is my query

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`

When I add the second left join in this case of the likes , the results of the num_comments and num_likes came wrong. How can I perform this kind of query?

The query builds up to give you every possible combination of comments and likes on a post.

Probably easiest to just use 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`

Note that your query is relying on a feature of MySQL but which would cause an error in most flavours of SQL. For most flavours of SQL you need to list ALL the non aggregate columns in the GROUP BY clause.

Use Distinct clause because it will display combination of like and comment table data

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`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM