查询帮助? MySQL,LEFT JOIN,GROUP BY,缺少数据

时间:2011-05-25 23:28:48

标签: mysql sql join

如何更改此查询,以便在添加2011-01-02行后​​仍然显示2011-01-01收到的0 flotsam?

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

1 个答案:

答案 0 :(得分:1)

使用:

   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子句中提供的条件。 WHERE子句中的条件(对于OUTER JOINed的表)在 JOIN后应用