即使没有记录,也请选择日期范围内的所有记录

时间:2017-01-11 08:14:42

标签: mysql date

我有一个员工及其出勤的数据库。我必须创建出勤日期范围报告。

出勤数据库表

Database Schema

我正在使用以下查询

SELECT a.* FROM attendance a WHERE a.user_id=10 AND (a.date BETWEEN '2017-01-06' AND '2017-01-10')

结果: - Result by My Query

我还想要所有给定日期范围的记录,但是数据库中没有一些日期记录,我希望那些日期显示空值对应于那些日期,如下图所示。

Final Output I want

1 个答案:

答案 0 :(得分:0)

试试这个。我无法运行它,但想法是根据此answer生成日期范围。

  1. 将此日期范围用作派生表d

  2. 执行d left join attendance添加您的条件,这样您就会获得匹配数据的所有列,而null则不匹配数据。

  3. 除了员工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