如何更改此查询,使其在添加 2011-01-02 行后仍显示 2011-01-01 收到的 0 个漂浮物?
mysql> SELECT * FROM Items;
+---------+
| Name |
+---------+
| widgets |
| things |
| stuff |
| flotsam |
| jetsam |
+---------+
mysql> SELECT * FROM Received;
+---------+---------------+-------------+----------+
| Name | invoiceNumber | invoiceDate | Quantity |
+---------+---------------+-------------+----------+
| widgets | 1 | 2011-01-01 | 1 |
| widgets | 2 | 2011-01-01 | 2 |
| things | 3 | 2011-01-01 | 3 |
| things | 4 | 2011-01-01 | 4 |
| stuff | 5 | 2011-01-01 | 5 |
| jetsam | 7 | 2011-01-01 | 7 |
+---------+---------------+-------------+----------+
mysql> SELECT Name, IFNULL(SUM(Quantity),0)
-> FROM Items AS I
-> LEFT JOIN Received AS R
-> USING (Name)
-> WHERE invoiceDate='2011-01-01' OR invoiceDate IS NULL
-> GROUP BY Name;
+---------+-------------------------+
| Name | IFNULL(SUM(Quantity),0) |
+---------+-------------------------+
| flotsam | 0 |
| jetsam | 7 |
| stuff | 5 |
| things | 7 |
| widgets | 3 |
+---------+-------------------------+
mysql> INSERT INTO Received VALUES ('flotsam',8,'2011-01-02',8);
mysql> SELECT Name, IFNULL(SUM(Quantity),0)
-> FROM Items AS I
-> LEFT JOIN Received AS R
-> USING (Name)
-> WHERE invoiceDate='2011-01-01' OR invoiceDate IS NULL
-> GROUP BY Name;
+---------+-------------------------+
| Name | IFNULL(SUM(Quantity),0) |
+---------+-------------------------+
| jetsam | 7 |
| stuff | 5 |
| things | 7 |
| widgets | 3 |
+---------+-------------------------+
最佳答案
用途:
SELECT i.name,
COALESCE(SUM(r.quantity), 0) AS total_quantity
FROM ITEMS i
LEFT JOIN RECEIVED r ON r.name = i.name
AND r.invoicedate = '2011-01-01'
GROUP BY i.name
在 JOIN 之前应用 OUTER JOIN(LEFT、RIGHT)的 ON
子句中提供的条件。针对要进行 OUTER JOIN 的表,WHERE 子句中的条件将在 JOIN 之后应用。
关于mysql - 查询帮助? MySQL、LEFT JOIN、GROUP BY、缺失数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6132115/