1

我有查询问题

SELECT
    IFNULL(SUM(a.x), 0) AS x,
    IFNULL(COUNT(*), 0) AS num
FROM a AS a
WHERE (a.`time` >= DATE_SUB(CURDATE(), INTERVAL 7 DAY))
GROUP BY DAY(a.time)

没关系,但是当确切的日期没有记录时,这天不返回。我需要返回0。怎么办?

4

1 回答 1

6
SELECT
    COALESCE(SUM(a.x), 0) AS x,
    COALESCE(COUNT(*), 0) AS num
FROM a AS a
WHERE (a.`time` >= DATE_SUB(CURDATE(), INTERVAL 7 DAY))
GROUP BY DAY(a.time)

COALESCE - 返回列表中的第一个非空值

但是,我认为您应该在处理@DevZer0 建议的数据时处理这个问题。

于 2013-07-27T11:00:41.660 回答