简体   繁体   中英

How to left join multiple one to many tables in mysql?

i have a problem with joining three tables in mysql.

lets say we have a table named posts which I keep my entries in it, i have a table named likes which i store user_id's and post_id's in and a third table named comments which i store user_id's and post_id's and comment's text in it.

I need a query that fetches list of my entries, with number of likes and comments for each entry.

Im using this query:

SELECT posts.id, count(comments.id) as total_comments, count(likes.id) as total_likes
FROM `posts`
LEFT OUTER JOIN comments ON comments.post_id = posts.id 
LEFT OUTER JOIN likes ON likes.post_id = posts.id
GROUP BY posts.id

but there is a problem with this query, if comments are empty for an item, likes count is just ok, but lets say if an entry has 2 comments and 4 likes, both total_comments and total_likes will be "8", meaning that mysql multiplies them. I'm confused and I dont know what whould I do.

Thanks in advace.

使用count(distinct comments.id)count(distinct likes.id) ,前提是这些id是唯一的。

Well this is one way to approach it (assuming mysql allows derived tables):

SELECT posts.id, comments.total_comments, likes.total_likes 
FROM `posts` 
LEFT OUTER JOIN (select post_id,  count(id) as total_comments from  comments) comments 
    ON comments.post_id = posts.id  
LEFT OUTER JOIN (select post_id,  count(id) as total_likes from  likes) likes 
    ON likes.post_id = posts.id 

You could also use correlated subqueries. You may want a case statment inthere to account for putting in a 0 when there are no matched records.

Let's try a correlated subquery:

SELECT posts.id, 
(select count(Id) from comments where post_id = posts.id) as total_comments, 
(select count(Id) from likes where post_id = posts.id) as total_likes 
FROM `posts` 

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