MYSQL查询显示来自多个表的产品数量

时间:2014-08-21 17:42:08

标签: mysql

我有这样的表

产品:

id_product  | product_name      | price

560         | AAA               | 1500 
561         | BBB               | 1750

attr:

id_attr | id_product | size | qty

100     | 560        | S    | 11

100     | 560        | M    | 9

100     | 560        | L    | 7

100     | 560        | XL   | 21

如何显示

product_name | qty_S | qty_M | qty_L | qty_XL | qty_total | price

AAA          | 11    | 9     | 7     | 21     | 48        | 1500

BBB          | 0     | 0     | 0     | 0      | 0         | 1750

我尝试像这样进行查询:

select p.*, a.*,

sum(a.qty) as qty_total,

[how_to_display_query] as qty_S,

[how_to_display_query] as qty_M,

[how_to_display_query] as qty_L,

[how_to_display_query] as qty_XL,


FROM product p LEFT JOIN attr a
ON p.id_product = a.id_product
group by p.id_product;

===============================================

请帮帮我,抱歉英语不好......谢谢

1 个答案:

答案 0 :(得分:0)

你想要转动结果..但是你不能在mysql中转移,因为它没有那个功能..所以你需要使用聚合和条件语句“伪造”一个转轴

这样做的方式是这样的.. MAX(CASE... ) SUM(CASE... )等..如果MAX(IF... ) SUM(IF... )也可以完成。

SELECT p.product_name
    SUM(a.qty) as qty_total,
    MAX(CASE size WHEN 'S' THEN qty ELSE 0 END) as qty_S,
    MAX(CASE size WHEN 'M' THEN qty ELSE 0 END) as qty_M,
    MAX(CASE size WHEN 'L' THEN qty ELSE 0 END) as qty_L,
    MAX(CASE size WHEN 'XL' THEN qty ELSE 0 END) as qty_XL,
    p.price
FROM product p 
LEFT JOIN attr a ON p.id_product = a.id_product
GROUP BY by p.id_product;

我在这里使用了MAX(),因为你似乎只得到一个数字..如果你想要添加多个数量,那么你可以将MAX更改为SUM