简体   繁体   中英

How to fill empty value when no record in that day using MySQL group by

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 

I don't want use PROCEDURE like this: http://stackoverflow.com/questions/7252460/mysql-group-by-and-fill-empty-rows

I don't want to create a whole day containing table like this: http://stackoverflow.com/questions/5988179/mysql-group-by-date-how-to-return-results-when-no-rows

I can use SELECT @@global.time_zone, @@session.time_zone; in PHP and after the MySQL query result is out, I make PHP to the same timezone as MySQL, and fill the date by PHP. But is it a way I can just do it in MySQL way?

You can use a trick to generate virtual table having all the dates you need with another table (replace aux with any table in your DB with 31 recored at least):

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

And then join you table on it:

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`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM