MYSQL 连接两个表并合并行值
MYSQL Join two tables and combine row values
我有一个包含两个表的 MySQL 数据库:
Table 1:
Product_ID | Product_Name | Product_Description
------------------------------------------------
1 | Coca-Cola | Coke description.
2 | Pepsi | Pepsi description.
3 | Fanta | Fanta description
...
Table 2:
Product_ID | Product_SKU | Product_Size | Product_Price
------------------------------------------------
1 | COKE330 | 330ml | 0.79
1 | COKE500 | 500ml | 1.29
2 | PEPS330 | 330ml | 0.59
2 | PEPS500 | 500ml | 0.99
...
我想查询数据库并将这两个表连接在一起,但合并具有相同产品 ID 的重复行,因此返回的结果最终看起来像:
Product_ID | Product_Name | Product_Sizes | Product_Prices | Product_Description
---------------------------------------------------------------------------------
1 | Coca-Cola | 330ml, 500ml | 0.79, 1.29 | Coke description.
2 | Pepsi | 330ml, 500ml | 0.59, 0.99 | Pepsi description.
...
提前致谢
您可以对行进行分组并使用 GROUP_CONCAT()
到 assemble 分组值,如:
select
a.product_id,
max(a.product_name),
group_concat(b.product_size) as product_sizes,
group_concat(b.product_price) as product_prices,
a.product_description
from table1 a
join table2 b on b.product_id = a.product_id
group by a.product_id
我有一个包含两个表的 MySQL 数据库:
Table 1:
Product_ID | Product_Name | Product_Description
------------------------------------------------
1 | Coca-Cola | Coke description.
2 | Pepsi | Pepsi description.
3 | Fanta | Fanta description
...
Table 2:
Product_ID | Product_SKU | Product_Size | Product_Price
------------------------------------------------
1 | COKE330 | 330ml | 0.79
1 | COKE500 | 500ml | 1.29
2 | PEPS330 | 330ml | 0.59
2 | PEPS500 | 500ml | 0.99
...
我想查询数据库并将这两个表连接在一起,但合并具有相同产品 ID 的重复行,因此返回的结果最终看起来像:
Product_ID | Product_Name | Product_Sizes | Product_Prices | Product_Description
---------------------------------------------------------------------------------
1 | Coca-Cola | 330ml, 500ml | 0.79, 1.29 | Coke description.
2 | Pepsi | 330ml, 500ml | 0.59, 0.99 | Pepsi description.
...
提前致谢
您可以对行进行分组并使用 GROUP_CONCAT()
到 assemble 分组值,如:
select
a.product_id,
max(a.product_name),
group_concat(b.product_size) as product_sizes,
group_concat(b.product_price) as product_prices,
a.product_description
from table1 a
join table2 b on b.product_id = a.product_id
group by a.product_id