Carlos Vázquez Carlos Vázquez - 2 months ago 6
MySQL Question

MySQL - Group_concat querywithout group

I have 3 tables: design, category and design_category

And I need, a row by each design with diferent category, but with a column with the concat categories. I do the next:

SELECT d.id, d.name, c.id, GROUP_CONCAT(c.id)
FROM design d
LEFT JOIN design_category dc ON dc.design_id = d.id
LEFT JOIN category c ON dc.category_id = c.id
GROUP BY d.id


+----+-----------------------------------+------+--------------------+
| id | name | id | GROUP_CONCAT(c.id) |
+----+-----------------------------------+------+--------------------+
| 2 | Design 1 | 177 | 177,178 |
| 4 | Design 2 | 179 | 179,177,178 |
| 5 | Design 3 | 177 | 177,178 |
| 6 | Design 4 | 177 | 177,178 |
| 7 | Design 5 | 177 | 177,178 |
| 8 | Design 6 | 181 | 181,180 |
+----+-----------------------------------+------+--------------------+


But I wont something like that:

+----+-----------------------------------+------+--------------------+
| id | name | id | GROUP_CONCAT(c.id) |
+----+-----------------------------------+------+--------------------+
| 2 | Design 1 | 177 | 177,178 |
| 2 | Design 1 | 178 | 177,178 |
| 4 | Design 2 | 177 | 179,177,178 |
| 4 | Design 2 | 178 | 179,177,178 |
| 4 | Design 2 | 179 | 179,177,178 |
| 5 | Design 3 | 177 | 177,178 |
| 5 | Design 3 | 178 | 177,178 |
| 6 | Design 4 | 177 | 177,178 |
| 6 | Design 4 | 178 | 177,178 |
| 7 | Design 5 | 177 | 177,178 |
| 7 | Design 5 | 178 | 177,178 |
| 8 | Design 6 | 180 | 181,180 |
| 8 | Design 6 | 181 | 181,180 |
+----+-----------------------------------+------+--------------------+


It's possible in MySQL?

Answer

This should work:

select x.id, x.name, y.id, z.grouped_id from FROM design x
LEFT JOIN design_category xy ON xy.design_id = x.id 
LEFT JOIN category y ON xy.category_id = y.id  
left join(
SELECT d.id id , GROUP_CONCAT(c.id) grouped_id
FROM design d
LEFT JOIN design_category dc ON dc.design_id = d.id 
LEFT JOIN category c ON dc.category_id = c.id  
GROUP BY d.id) zon z.id= x.id
Comments