Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL Left Join Many to One Row

To simplify my problem: Let's say I have 3 tables.

Rooms              People                    Things
--------           --------                  --------
id| name           id | name | fk_rooms      id | name | fk_rooms
-----------        ---------------------     ---------------------
1 | kitchen        1  | John | 1              1 | TV   | 2
2 | bedroom        2  | Mary | 2              2 | bed  | 2
                   3  | Andy | 1              3 | sink | 1
                   4  | Laura| 1

Now I'm doing something like:

SELECT r.name AS room_name, p.name AS name, t.name AS thing FROM Rooms r 
LEFT JOIN People p ON p.fk_rooms = r.id
LEFT JOIN Things t ON t.fk_rooms = r.id

which in my case works perfectly except for a few that have many to one relationship with the "Rooms" table. So instead of new rows in the result set holding the different names for "People" and "Things" in relation to the "Rooms" table, I would like to receive only two rows:

1. kitchen, John, Andy, Laura, sink
2. bedroom, Mary, TV, bed

A GROUP BY on r.id will only select one row from each table. Any help is highly appreciated!

like image 944
NewInTheBusiness Avatar asked May 21 '13 23:05

NewInTheBusiness


People also ask

Does LEFT join change number of rows?

Left joins can increase the number of rows in the left table if there are multiple matches in the right table.

Does LEFT join return multiple rows?

Introduction to SQL Server LEFT JOIN clause The LEFT JOIN is a clause of the SELECT statement. The LEFT JOIN clause allows you to query data from multiple tables. The LEFT JOIN returns all rows from the left table and the matching rows from the right table.

How does LEFT join result in more rows?

There are two line items for ID 1003 in the second table, so the result of the join will be 2 line items. So, if your secondary tables have more than one row for the key you're joining with, then the result of the join will be multiple rows, resulting in more rows than the left table.

Does LEFT join allow duplicates?

Again, if we perform a left outer join where date = date, each row from Table 5 will join on to every matching row from Table 4. However, in this case, the join will result in 4 rows of duplicate dates in the joined DataSet (see Table 6).


1 Answers

Here it is what you're looking for:

SELECT r.name AS room_name, 
   GROUP_CONCAT(p.name separator ',') AS people_name, 
   GROUP_CONCAT(t.name separator ',') AS things
FROM Rooms r 
LEFT JOIN People p ON p.fk_rooms = r.id
LEFT JOIN Things t ON t.fk_rooms = r.id
GROUP BY r.id
like image 198
medina Avatar answered Sep 19 '22 00:09

medina