获取不同表中的父类别总和(price)

vwoqyblh  于 2021-06-18  发布在  Mysql
关注(0)|答案(1)|浏览(348)

我试图得到在一个特定的月份和年份的所有父类别的总价格。父类别是父类别id==0的任何类别。我的问题如下:

SELECT
    ROUND(SUM(od.total_price)) as price, 
    c.parent_id as pId,
    c1.name
FROM a_orders o 
    INNER JOIN a_order_details as od on o.id = od.order_id 
    INNER JOIN a_product as p on p.id = od.product_id 
    INNER JOIN a_category as c on c.id = p.category_id
    LEFT OUTER JOIN a_category c1 ON c.parent_id = c1.id
WHERE YEAR(order_date) = 2018
    AND o.STAT = 'Y' 
    AND MONTH(order_date) = 6
GROUP BY c.parent_id;

我得到的父类别只是有一个价格,但我需要得到所有的父类别,如果没有价格结果应该是0。
我的小提琴是->http://sqlfiddle.com/#!9/b9f4c1/1号
我的结果是这样的:

price   pId  name
410     1    T-SHIRT
400     2    JEANS

但应该是这样的:

price   pId  name
410     1    T-SHIRT
400     2    JEANS
0       6    SHOES
snz8szmq

snz8szmq1#

要做到这一点,你需要改变你的逻辑。首先选择所有父类别,然后加入订单数据。这样您就可以确保结果中包含所有所需的类别。
有很多方法可以做到这一点-在这里,我创建了一个包含所有订单数据的子查询,然后 LEFT JOIN 使用类别表:

SELECT
    IFNULL(ROUND(SUM(orders.total_price)),0) AS price, 
    c.id AS pId,
    c.name
FROM a_category c
    LEFT JOIN (
        SELECT od.total_price, c.parent_id
        FROM a_orders o 
            INNER JOIN a_order_details od ON o.id = od.order_id 
            INNER JOIN a_product p ON p.id = od.product_id 
            INNER JOIN a_category c ON c.id = p.category_id
        WHERE YEAR(order_date) = 2018
            AND o.STAT = 'Y' 
            AND MONTH(order_date) = 6
    ) orders ON orders.parent_id = c.id
WHERE c.parent_id = 0
GROUP BY c.id;

http://sqlfiddle.com/#!9/b9f4c1/3型

相关问题