Get total views per day including leaving “0 views” for a day that has no record

前端 未结 2 1095
轻奢々
轻奢々 2021-01-22 07:01

I am creating a graph where I can get the total views everyday for a certain range, or as long it goes back.

The problem I am having is to fill a default number of

相关标签:
2条回答
  • 2021-01-22 07:06

    When I did this a couple of years ago I created an empty array with the date as key and the default value 0. Then I simply looped through the result att changed the value for those dates I had.

    for each($result as $row){
       $date_stats_array[$row['date']] = $row['value'];
    }
    
    0 讨论(0)
  • 2021-01-22 07:21

    In situations like this I create a temporary table which I fill with all the dates you want. After that, you can use that table to join your original query against.

    To fill the table you can use this procedure:

    DROP PROCEDURE IF EXISTS filldates;
    DELIMITER |
    CREATE PROCEDURE filldates(dateStart DATE, dateEnd DATE)
    BEGIN
      WHILE dateStart <= dateEnd DO
        INSERT INTO tablename (_date) VALUES (dateStart);
        SET dateStart = date_add(dateStart, INTERVAL 1 DAY);
      END WHILE;
    END;
    |
    DELIMITER ;
    CALL filldates('2011-01-01','2011-12-31');
    

    Courtesy of https://stackoverflow.com/a/10132142/375087

    0 讨论(0)
提交回复
热议问题