2014-11-25 119 views
0

我在两个表得到的数据:MySQL的 - 合并两个表

表产品

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,我不知道每个产品的所有细节(如果我知道比我会把一些额外的列到产品表)。细节每天都在变化。

+0

你需要工作你的表结构有些。这将帮助你更好地操纵你的结果。 – 2014-11-25 14:22:06

+0

你为什么要合并这两个表? – Jaylen 2014-11-25 14:22:18

+0

您需要了解3NF – Andrew 2014-11-25 14:31:48

回答

2

我会使用条件聚集和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; 
-1

当我明白这个问题,你想用数据的结果表两个表:

select products.ID, products.title, details.* 
from products 
inner join details 
on details.productID = products.ID;