将表的列一对多连接

将表的列一对多连接

我有2张桌子(person + person_products

每个人至少有一种产品。

样本人表:

person_id | name
------------------
1         | Alice
2         | Peter
3         | James


样本人员_产品表:

id | person_id | description | price
------------------------------------
1  | 1         | iphone 5    | 100
2  | 1         | iphone 6    | 200
3  | 1         | samsung     | 300
4  | 2         | tv          | 110
5  | 3         | oven        | 250
6  | 3         | microwave   | 260


我要执行以下操作:

SELECT p.person_id,
some_concat_product_descriptions,
some_concat_product_prices
FROM person p
LEFT JOIN person_products p on p.person_id = pp.person_id


预期结果:

person_id | concat_product_descriptions | concat_product_prices
---------------------------------------------------------------
1         | iphone 5, iphone 6, samsung | 100, 200, 300
2         | tv                          | 110
3         | oven, microwave             | 250, 260


我该如何实现?

最佳答案

使用group_concat

SELECT p.person_id,
       group_concat(pp.description order by pp.description) as concat_product_descriptions,
       group_concat(pp.price order by pp.description) as concat_product_prices
FROM person p
LEFT JOIN person_products pp on p.person_id = pp.person_id
GROUP BY p.person_id

关于mysql - MySQL:将表的列一对多连接,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52041385/

10-10 13:03