[英]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.