MySQL在连接表上返回Null = 0,并在一个表上使用过滤器

时间:2014-07-28 11:52:13

标签: mysql join null

我试图返回一个结果,该结果为我提供了一段时间内每天的总交易价值。我有2张桌子,'日历'其中包含2013-12-31和2014-12-31之间的所有日期。还有第二个存储所有' customer_transactions'的表格。我希望我的结果看起来像:

DATE         |      sum(value)
...                   ...
2014-07-28            10
2014-07-27            7
2014-07-26            0
2014-07-25            0
2014-07-24            5
...                   ...

我构建了一个有效的查询:

SELECT calendar.datefield AS DATE,
       IFNULL(SUM(ct.value),0) AS total_sales
FROM calendar
LEFT JOIN customer_transactions as ct ON (calendar.datefield = from_unixtime(ct.date_edit, '%Y-%m-%d'))
WHERE (calendar.datefield BETWEEN ('2013-12-31') AND ('2014-12-31'))
GROUP BY DATE

但是,我想根据customer_transactions表中的列(例如customer_id = 5)过滤我的结果,仅返回某个客户的交易

如果我按如下方式添加WHERE子句:

    SELECT calendar.datefield AS DATE,
               IFNULL(SUM(ct.value),0) AS total_sales
    FROM calendar
    LEFT JOIN customer_transactions as ct ON (calendar.datefield = from_unixtime(ct.date_edit, '%Y-%m-%d'))
    WHERE (calendar.datefield BETWEEN ('2013-12-01') AND ('2014-07-28'))
    AND ct.customer_id=5
    GROUP BY DATE

我的null = 0值不再显示。我已经搜索了高低,但找不到我做错的事情,我认为这与JOIN有关。

注意:日期存储在' customer_transactions' table是Unix时间戳,在日历'

中为2014-01-01格式

1 个答案:

答案 0 :(得分:2)

您已将条件添加到查询的错误部分。

LEFT JOIN在没有事务的情况下使customer_transactionscalendar记录的所有列都为空。将ct.customer_id=5添加到WHERE会删除所有这些已为空的值行,因为ct.customer_idNULL

您想将条件添加到LEFT JOIN

   SELECT calendar.datefield AS date, IFNULL(SUM(ct.value),0) AS total_sales
     FROM calendar
LEFT JOIN customer_transactions as ct 
       ON (calendar.datefield = from_unixtime(ct.date_edit, '%Y-%m-%d'))
      AND ct.customer_id=5
    WHERE (calendar.datefield BETWEEN ('2013-12-31') AND ('2014-12-31'))
 GROUP BY date