我有一个员工及其出勤的数据库。我必须创建出勤日期范围报告。
出勤数据库表
我正在使用以下查询
SELECT a.* FROM attendance a WHERE a.user_id=10 AND (a.date BETWEEN '2017-01-06' AND '2017-01-10')
我还想要所有给定日期范围的记录,但是数据库中没有一些日期记录,我希望那些日期显示空值对应于那些日期,如下图所示。
答案 0 :(得分:0)
试试这个。我无法运行它,但想法是根据此answer生成日期范围。
将此日期范围用作派生表d
。
执行d
left join
attendance
添加您的条件,这样您就会获得匹配数据的所有列,而null
则不匹配数据。
除了员工ID之外,这将为您提供其余数据。我建议你可以在选择查询中对其进行硬编码。
select * from
(select a.Date
from
(
select curdate() - INTERVAL (a.a + (10 * b.a) + (100 * c.a)) DAY as Date
from (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as a
cross join (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as b
cross join (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as c
) a
where a.Date between '2017-01-06' AND '2017-01-10'
) d
left join
attendance a
on d.date = a.date
where
a.user_id=10