MySQL:将表的列一对多连接

时间:2018-08-27 14:20:09

标签: mysql concatenation

我有2张桌子(person + person_products

每个人至少有一种产品。

样本人表:

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

person_products表样本:

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

我该如何实现?

2 个答案:

答案 0 :(得分:1)

使用group_concat

<DataTrigger Binding="{Binding Contains}" Value="True">
    <Setter Property="Background" Value="Red"/>
</DataTrigger>

答案 1 :(得分:-1)

使用group_concat aggregation function。完全不需要加入。

select 
  person_id,
  group_concat(description) separator ', ' as concat_product_descriptions,
  group_concat(price) separator ', ' as concat_product_prices
group by 
  person_id