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

a 夏天 提交于 2019-12-23 10:29:17

问题


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.


回答1:


Use count(distinct comments.id) and count(distinct likes.id), provided these ids are unique.




回答2:


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` 


来源:https://stackoverflow.com/questions/4650914/how-to-left-join-multiple-one-to-many-tables-in-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!