[英]Mysql - merge two tables
我在两个表中有数据:
餐桌产品
ID | title
1 | T-shirt
2 | Pants
...
和表的详细信息
productID | key | value
1 | color | green
1 | size | M
1 | size | L
2 | color | white
2 | color | black
2 | brand | n/a
...
因此,表中的每个产品都有很多细节。 我想写给我结果的SQL:
ID | title | color | size | brand
1 | T-shirt | green | M,L |
2 | Pants | white,black | | n/a
现在,我的第一个SQL是:
SELECT * FROM products;
然后每次我调用时都在while循环中:
SELECT * FROM details WHERE productID={id}
然后将数据合并在一起。 有没有简单的方法? 谢谢!
编辑:数据导入到mysql,我不知道每个产品的所有详细信息(如果我知道的话,我会在产品表中添加一些额外的列)。 而且细节每天都在变化。
我将使用条件聚合和group_concat()
进行此操作:
select p.id, p.title,
group_concat(case when key = 'color' then value end) as colors,
group_concat(case when key = 'size' then value end) as sizes,
group_concat(case when key = 'brand' then value end) as brands
from products p join
details d
on p.id = d.productid
group by p.id, p.title;
据我了解的问题,您想要一个包含两个表中的数据的结果表:
select products.ID, products.title, details.*
from products
inner join details
on details.productID = products.ID;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.