如何使用MySQL group by在当天没有记录时填充空值

时间:2015-04-16 03:11:20

标签: php mysql

SELECT `Date`, SUM(Clicks) AS Clicks, DAY(LAST_DAY(NOW()))  AS Monthdays
FROM myTbl 
WHERE ( DATE BETWEEN DATE_FORMAT(NOW(), '%Y-%m-01') AND NOW() )      
AND MoverID = 123  GROUP BY `Date` ASC 

我不想像这样使用PROCEDURE:http://stackoverflow.com/questions/7252460/mysql-group-by-and-fill-empty-rows

我不想创建一整天包含这样的表:http://stackoverflow.com/questions/5988179/mysql-group-by-date-how-to-return-results-when-no-rows

我可以在PHP中使用SELECT @@global.time_zone, @@session.time_zone;,在MySQL查询结果出来之后,我将PHP与MySQL的时区相同,并用PHP填写日期。但这是一种我可以用MySQL方式做到的方式吗?

1 个答案:

答案 0 :(得分:2)

您可以使用技巧生成具有所需日期的虚拟表与另一个表(将aux替换为数据库中的任何表,至少31个记录):

SELECT CONVERT(@d := DATE_ADD(@d, INTERVAL 1 DAY), DATE) AS `d`
FROM
    `aux`,
    (SELECT @d := DATE_SUB(CONVERT(DATE_FORMAT(NOW(), '%Y-%m-01'), DATETIME), INTERVAL 1 DAY)) `x`
WHERE
    @d < DATE_SUB(NOW(), INTERVAL 1 DAY)
LIMIT
    31

然后加入你的表格:

SELECT
    `aux`.`d` as `Date`,
    SUM(IFNULL(`Clicks`, 0))AS `Clicks`,
    DAY(LAST_DAY(NOW())) AS `Monthdays`
FROM (
    SELECT CONVERT(@d := DATE_ADD(@d, INTERVAL 1 DAY), DATE) AS `d`
    FROM
        `aux`,
        (SELECT @d := DATE_SUB(CONVERT(DATE_FORMAT(NOW(), '%Y-%m-01'), DATETIME), INTERVAL 1 DAY)) `x`
    WHERE
        @d < DATE_SUB(NOW(), INTERVAL 1 DAY)
    LIMIT
        31
) aux
LEFT JOIN
    myTbl
    ON `Date` = `aux`.`d`
GROUP BY `aux`.`d`