Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 611
Sallar Avatar asked Jan 10 '11 20:01

Sallar


People also ask

How join multiple tables with LEFT join?

Syntax For Left Join:SELECT column names FROM table1 LEFT JOIN table2 ON table1. matching_column = table2. matching_column; Note: For example, if you have a left table with 10 rows, you are guaranteed to have at least 10 rows after applying join operation on two tables.

Is Left join one to many?

SQL LEFT JOIN examples Each location belongs to one and only one country while each country can have zero or more locations. The relationship between the countries and locations tables is one-to-many.

Can you join multiple tables in mysql?

It is possible to use multiple join statements together to join more than one table at the same time. To do that you add a second INNER JOIN statement and a second ON statement to indicate the third table and the second relationship.


1 Answers

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

like image 71
GolezTrol Avatar answered Oct 31 '22 02:10

GolezTrol