开发者

Query help? MySQL, LEFT JOIN, GROUP BY, missing data

开发者 https://www.devze.com 2023-03-08 05:36 出处:网络
How do I change this query so that it still shows 0 flotsam received on 2011-01-01 after the 2011-01-02 row is added?

How do I change this query so that it still shows 0 flotsam received on 2011-01-01 after the 2011-01-02 row is added?

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 | 
+---------+-------------------------+


Use:

   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

Criteria provided in the ON clause of an OUTER JOIN (LEFT, RIGHT) is applied before the JOIN. Criteria in the WHERE clause, against a table being OUTER JOINed to, is applied after the JOIN.

0

精彩评论

暂无评论...
验证码 换一张
取 消