Skip to content
Advertisement

query for join two column and get one row per left with column that have array of right table refrenced to left table row

hellow.I have a tablt product like this

+-------+-------+
|  id   |  name |
+-------+-------+
+-------+-------+
|   1   | shirt |
+-------+-------+

color table like below:
+-------+--------+
|   id  |  color |
+-------+--------+
+-------+--------+
|   1   |  red   |
+-------+--------+
+-------+--------+
|   2   | yellow |
+-------+--------+
+-------+--------+
|   3   |  black |
+-------+--------+

and shirt_color table:

+------------+----------+
| product_id | color_id |
+------------+----------+
+------------+----------+
| 1          | 1        |
+------------+----------+
+------------+----------+
| 1          | 2        |
+------------+----------+
+------------+----------+
| 1          | 3        | 
+------------+----------+

I want to write a query to get all products and its colors (but all colors in one array column) like this below :

+-------+-------+---------------+
| pro_id|  name |    colors     |
+-------+-------+---------------+
+------+-------+----------------+
|    1 | shirt |red,yellow,black|
+------+-------+----------------+

Advertisement

Answer

use GROUP_CONCAT:

select a.id as pro_id,  a.name,
GROUP_CONCAT ( color ) as colors
from product a inner join shirt_color b on a.id = b.product_id 
inner join color c on c.id = b.color_id
group by a.id,  a.name
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement