[英]MySQL: concatenate columns of tables one-to-many
I have 2 tables ( person
+ person_products
) 我有2张桌子(
person
+ person_products
)
where each person has at least 1 product. 每个人至少有一种产品。
Sample person table: 样本人表:
person_id | name
------------------
1 | Alice
2 | Peter
3 | James
Sample person_products table: 样本人员_产品表:
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
I want to do the following: 我要执行以下操作:
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
Expected result: 预期结果:
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
How can I achieve this? 我该如何实现?
Use group_concat 使用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
Use group_concat aggregation function . 使用group_concat聚合函数 。 A join is is not needed at all.
根本不需要联接。
select
person_id,
group_concat(description) separator ', ' as concat_product_descriptions,
group_concat(price) separator ', ' as concat_product_prices
group by
person_id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.