我有这样的看法:
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
表上却存在{1>。
例如:
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 |
+-----------+--------------+------------+
我在这里想念什么?任何建议,将不胜感激:)
答案 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
–您想要的结果。