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

前端 未结 2 1096
轻奢々
轻奢々 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: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

提交回复
热议问题