Selecting Non-existent Data With MySQL

后端 未结 3 1875
攒了一身酷
攒了一身酷 2020-12-12 06:30

I\'m trying to select data between two date range. However not all data are being inserted daily. Below is sample of the table:

mysql> SELECT * FROM atten         


        
相关标签:
3条回答
  • 2020-12-12 06:38

    MySQL cannot generate data that isn't there. If you want non-existent dates, you'll need to have a temporary table that contains the full date range you join against. Another alternative is to maintain a server-side variable and do some date math for each row, which is ugly

    select @dateval := '2012-07-02';
    SELECT @dateval := @dateval + INTERVAL 1 DAY from ...
    
    0 讨论(0)
  • 2020-12-12 06:45

    This is a common problem with a simple solution.

    Create a regular table, say REF_DATE, and store in it all dates for like 3 years or whatever time span you would need.

    Then use this table on the left of a LEFT OUTER JOIN

    SELECT REF.date,IFNULL(A.total,0) as total FROM REF_DATE REF 
    LEFT OUTER JOIN attendance 
    ON REF.date=A.date
    A WHERE REF.date BETWEEN '2012-07-02' AND '2012-07-04';
    

    DATE is a keyword in MySQL, I have used it here for readability. Use a different column name.

    0 讨论(0)
  • 2020-12-12 07:00

    You can enumerate dates as derived pseudo-table (with UNION) and then join it with your data

    SELECT dates.date, COALESCE(attendance.total,0) AS total FROM (
    SELECT '2012-07-02' AS date
    UNION ALL SELECT '2012-07-03'
    UNION ALL SELECT '2012-07-04'
    ) AS dates
    LEFT JOIN attendance USING(date)
    

    Edit: added COALESCE to return 0 instead of NULL on missing records.

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