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
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 ...
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.
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.