带有count的SQL嵌套子查询

时间:2016-06-20 15:46:39

标签: mysql sql nested

是否有更方便,更简单的方法来编写以下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`

2 个答案:

答案 0 :(得分:1)

您可以根据/var/log/apache2/akeneo-pim_error.log

进行条件SUM()聚合
Payment_method

我还添加了别名以使其更具可读性,并将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 BY而不是P.NameP.Id语句中没有显示P.Id,而SELECT允许这样做,结果会留给编译器,这可能会给您带来意想不到的结果。

答案 1 :(得分: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评论,我同意可以简化为:

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