SELECT语句中的子查询(MySQL)

时间:2012-02-15 18:16:35

标签: mysql select subquery

我正在创建一个SQL语句,它将返回一个产品列表以及我在每个商店中可以找到的每个产品的数量。

我的表格结构(带有一些样本数据)如下:

productID - size - color - stock - storeID  
1         - S    - RED01 - 1     - BCN   
1         - S    - RED01 - 3     - MAD   
2         - S    - YEL02 - 0     - BCN   
2         - S    - YEL02 - 2     - MAD   
1         - S    - RED01 - 1     - BCN2  

我需要一个与此类似的结果:

productID - size - stockBCN (BCN + BCN2) - stockMAD  
1         - S    - 2                     - 3  
2         - S    - 0                     - 2

我使用此声明,仅适用于独特的产品

SELECT DISTINCT prodID, size,
    (SELECT SUM(stock) FROM stocks WHERE storeID IN ('BCN','BCN2') AND prodID = 1 AND size = 'S' AND color = 'RED01' GROUP BY prodID, size, color) AS stockBCN,
    (SELECT SUM(stock) FROM stocks WHERE storeID = 'MAD' AND prodID = 1 AND size = 'S' AND color = 'RED01' GROUP BY prodID, size, color) AS stockMAD,
FROM stocks WHERE storeID IN ('BCN','BCN2','MAD')
AND prodID = (1) AND size = 'S' AND color = 'RED01'

如何更改它以使其适用于表中的所有行?

2 个答案:

答案 0 :(得分:8)

您可能希望利用GROUP BY子句而不是DISTINCT那里,即:

SELECT productId, Size,
SUM(CASE WHEN storeID IN ('BCN', 'BCN2') THEN stock ELSE 0 END) AS stockBCN,
SUM(CASE WHEN storeID = 'MAD' THEN stock ELSE 0 END) AS stockMAD
FROM stocks
GROUP BY productId, Size

答案 1 :(得分:1)

IMO使用案例陈述的黄金时间

Select productID, Size, Color,
SUM(CASE WHEN STOREID IN ('BCN','BCN2') THEN stock else 0 end) as StockBCN,
SUM(Case WHEN STOREID = 'MAD') THEN stock else 0 end) as StockMad
FROM STOCKS 
Where storeID in ('BCN', 'BCN2','MAD')
GROUP BY productID, Size, Color