mysql查询左连接三个表显示所有数据

时间:2014-09-19 01:27:18

标签: mysql

我在使用左连接时遇到了3个表的问题。我有员工表,考勤表和休假表

我有一张员工表

雇员

employee_id   | employee_name
     1        |  George

出勤

 employee_id    |  date
       1        | 2014-01-02
       1        | 2014-01-03

leave_schedule

employee_id    |     leave_datedate  |    reason
       1       |       2014-01-01    |  sick leave
       1       |       2014-01-02    |  vacation leave

这是我的查询

select e.employee_id, e.employee_name, a.date, l.leave_date, l.reason from employee e left join attendance a ON a.employee_id = e.employee_id left join leave_schedule l on l.employee_id = e.employee_id and a.date = l.leave_date where e.employee_id = 1

结果是

employee_id   |   employee_name  |  date         |   leave_date   | reason
    1         |      george      |  2014-01-02   |    2014-01-02  | vacation leave
    1         |      george      |  2014-01-03   |    null        |  null

我想要包括病假。怎么做?它是完全外连接吗?

预期结果

    employee_id   |   employee_name  |  date         |   leave_date   | reason
        1         |      george      |  2014-01-01   |    2014-01-01  | sick leave
        1         |      george      |  2014-01-02   |    2014-01-02  | vacation leave
        1         |      george      |  2014-01-03   |    null        |  null

这是我的sqlfiddle

http://sqlfiddle.com/#!2/ad86b/1

1 个答案:

答案 0 :(得分:0)

您可以使用更复杂的查询来执行此操作。这是一种使用聚合和union all将假日期结合在一起的方法:

select e.employee_id, e.employee_name, al.date, al.leave_date, al.reason
from employee e left join
     (select employee_id, date, leave_date, max(reason) as reason
      from (select a.employee_id, a.date, a.date as leave_date, NULL as reason
            from attendance a
            union all
            select l.employee_id, l.leave_date, l.leave_date, l.reason
            from leave_schedule l
           ) al
      group by employee_id, date, leave_date
     ) al
     ON al.employee_id = e.employee_id
where e.employee_id = 1;