2016-06-20 249 views
1

是否有更方便更簡單的方法來編寫下列SQL代碼?SQL嵌套子查詢與計數

SELECT 
       products.name, 
       (SELECT COUNT(*) FROM `sales` WHERE sales.product_id = products.id AND sales.payment_method = 'debt') AS debt, 
       (SELECT COUNT(*) FROM `sales` WHERE sales.product_id = products.id AND sales.payment_method = 'cash') AS cash, 
       (SELECT COUNT(*) FROM `sales` WHERE sales.product_id = products.id AND sales.payment_method = 'free') AS free 

      FROM `sales`, `products` 
      WHERE `sales`.`product_id` = `products`.`id` 
      GROUP BY `products`.`id` 

回答

1

你可以基於該Payment_method條件SUM()聚集:

Select P.name, 
     Sum(Case When S.Payment_method = 'debt' Then 1 Else 0 End) As Debt, 
     Sum(Case When S.Payment_method = 'cash' Then 1 Else 0 End) As Cash, 
     Sum(Case When S.Payment_method = 'free' Then 1 Else 0 End) As Free 
From Sales  S 
Join Products P On S.Product_id = P.Id 
Group By P.Name 

我還添加了別名,使其更具可讀性,並改變了GROUP BYP.Name而非P.IdP.Id沒有出現在SELECT聲明中,而MySQL允許這樣做,結果留給編譯器,這可能會給你一些意想不到的東西。

+0

我可以添加另一個JOIN語句? '在S.time <= mytime上加入S' –

+0

應該將其作爲'WHERE'子句添加,而不是'JOIN'語句。 – Siyual

+0

您可能還想添加條件:'where S.Payment_method in('debt','cash','free'')。這不會改變結果,但可以提高性能。 –

1
SELECT p.name, 
     SUM(IF(s.payment_method = 'debt',1,0)) debt, 
     SUM(IF(s.payment_method = 'cash',1,0)) cash, 
     SUM(IF(s.payment_method = 'free',1,0)) free 
FROM products p 
JOIN sales s 
ON s.product_id = p.id 
GROUP BY p.id 

更新據@jpw評論,我同意,可以簡化爲:

​​
+2

您可以將條件進一步降低爲SUM(s.payment_method ='debt')',因爲MySQL會將布爾表達式評估爲1或0.) – jpw