我正在研究电子商务解决方案,我需要一些关于SQL查询的帮助。
我有这样的数据库设计。 这是实例
http://sqlfiddle.com/#!9/6d667/4
我正在使用此查询
SELECT p.id as product_id, p.name as product_name,
pv.name AS Varient_name, pvo.name AS Varient_Option_Name, pvoc.sku_id
FROM p p
LEFT JOIN pv pv ON (pv.p_id = p.id)
LEFT JOIN pvo pvo ON (pvo.pv_id = pv.id)
LEFT JOIN pvoc pvoc ON (pvoc.pvo_id = pvo.id)
此查询显示此类记录
我想要一个显示如下记录的查询:
这里有人可以帮忙吗? 等待谢谢
答案 0 :(得分:2)
您正在寻找的是表转置或转轴。
此查询为您执行此操作:
http://sqlfiddle.com/#!9/6d667/80
实际查询:
SELECT
p.id,
p.name,
MAX(CASE WHEN pv.name = 'Size' THEN pvo.name END) AS Size,
MAX(CASE WHEN pv.name = 'Color' THEN pvo.name END) AS Color,
MAX(CASE WHEN pv.name = 'Fabric' THEN pvo.name END) AS Fabric,
pvoc.sku_id,
COUNT(*) AS Quantity
FROM p AS p
LEFT JOIN pv AS pv
ON pv.p_id = p.id
LEFT JOIN pvo AS pvo
ON pvo.pv_id = pv.id
LEFT JOIN pvoc AS pvoc
ON pvoc.pvo_id = pvo.id
WHERE p.id = 1
GROUP BY p.id, p.name, pvoc.sku_id;
SQL Fiddle的结果:
| id | name | Size | Color | Fabric | sku_id | Quantity |
|----|------------|-------|--------|--------|----------------------------|----------|
| 1 | Men Hoodie | XL | (null) | (null) | (null) | 2 |
| 1 | Men Hoodie | M | Black | Cotton | MH-Size-M-Color-B-Fabric-C | 3 |
| 1 | Men Hoodie | M | Black | Jersy | MH-Size-M-Color-B-Fabric-J | 3 |
| 1 | Men Hoodie | M | White | Cotton | MH-Size-M-Color-W-Fabric-C | 3 |
| 1 | Men Hoodie | M | White | Jersy | MH-Size-M-Color-W-Fabric-J | 3 |
| 1 | Men Hoodie | Small | Black | Cotton | MH-Size-S-Color-B-Fabric-C | 3 |
| 1 | Men Hoodie | Small | Black | Jersy | MH-Size-S-Color-B-Fabric-J | 3 |
| 1 | Men Hoodie | Small | White | Cotton | MH-Size-S-Color-W-Fabric-C | 3 |
| 1 | Men Hoodie | Small | White | Jersy | MH-Size-S-Color-W-Fabric-J | 3 |
不知道为什么第一行有一个NULL值,但我刚刚使用了你给我们的小提琴,它已经有了一个NULL:)
现在你需要做的是 - 标准化尺寸名称(例如Small = S,Large = L),就是这样。
答案 1 :(得分:1)
查询:
SELECT cloth.name, color.name, fabric.name, size.name, connect_all.id_sku, connect_all.quantity
FROM connect_all
LEFT JOIN cloth
ON cloth.id = connect_all.id_cloth
LEFT JOIN color
ON color.id = connect_all.id_color
LEFT JOIN fabric
ON fabric.id = connect_all.id_fabric
LEFT JOIN size
ON size.id = connect_all.id_size
答案 2 :(得分:1)
http://sqlfiddle.com/#!9/6d667/201,您去了!
select p.id, p.name,
max(case when pv.name = 'size' then pvo.name end) as sizes,
max(case when pv.name = 'fabric' then pvo.name end) as fabrics,
max(case when pv.name = 'color' then pvo.name end) as çolours,
sku_id, count(*) as Qty
from p inner join pv
on p.id = pv.p_id
inner join pvo
on pv.id = pvo.pv_id
inner join pvoc
on pvo.id = pvoc.pvo_id
group by p.id, p.name,sku_id;