MySQL CASE ELSE在多联接选择语句中未返回0

时间:2019-03-06 20:02:06

标签: mysql sql

我有这样的看法:

VIEW `my_view` AS (
SELECT 
    t1.sku AS sku,
    FORMAT(SUM((CASE
            WHEN (t3.order_date > (CURDATE() - INTERVAL 42 DAY)) THEN t2.qty
            ELSE 0
        END)),
        0) AS qty_sold,
    FORMAT(SUM((CASE
            WHEN (t3.order_status_id = 3) THEN t2.qty
            ELSE 0
        END)),
        0) AS qty_ordered
FROM
    inventory_products t1
    JOIN inventory_sales t2 ON (t2.sku = t1.sku)
    JOIN inventory_orders t3 ON (t3.id = t2.order_id)
where t1.sku=1001 or t1.sku=1002 or t1.sku=1010
    GROUP BY t1.sku
)

该视图将按预期工作,并返回正确的结果,但当sku表上不存在inventory_sales时,该sku的行将完全不返回。

请注意,sku=1010表上不存在inventory_sales,但inventory_products表上却存在{

例如:

SELECT * FROM my_view 
WHERE sku=1001 OR sku=1002 OR sku=1010

返回此:

+-----------+--------------+------------+
|    sku    |   qty_sold   |qty_ordered |   
+-----------+--------------+------------+
|   1001    |      2       |     2      |
+-----------+--------------+------------+
|   1002    |      3       |     3      |
+-----------+--------------+------------+

但是我需要它来返回它:

+-----------+--------------+------------+
|    sku    |   qty_sold   |qty_ordered |   
+-----------+--------------+------------+
|   1001    |      2       |     2      |
+-----------+--------------+------------+
|   1002    |      3       |     3      |
+-----------+--------------+------------+
|   1010    |      0       |     0      |
+-----------+--------------+------------+

我在这里想念什么?任何建议,将不胜感激:)

1 个答案:

答案 0 :(得分:1)

我认为您只需要left join

SELECT . . .
FROM inventory_products t1 LEFT JOIN
     inventory_sales t2
     ON t2.sku = t1.sku LEFT JOIN
     inventory_orders t3
     ON t3.id = t2.order_id
WHERE t1.sku IN (1001, 1002, 1010)
GROUP BY t1.sku

我认为ELSE 0会将NULL变成0 –您想要的结果。