列出所有有leave title的员工,leave apply in join

List all employee with leave title, and leave apply in join

我有三个表:

Table 1: 员工

emp_id -KEY    emp_name    emp_join_date
 1841           test       2016-04-01
 1842           test1      2019-04-01

Table 2: leave_set

emp_id-KEY    start_date    end_date    nod    leave_type_id
 1841         2019-04-01    2019-04-02   2         2

Table3:leave_type

leave_type_id-KEY    leave_title
    1                   AL
    2                   SL
    3                   CME

我尝试了左连接,但如果 leave_set 没有值,那么它 return 在 Leave_Setleave_type 中的空值。

   SELECT 
       O.emp_id,  
       P.leave_title, I.leave_type_id, I.nod
   FROM 
       employee O 
   LEFT JOIN 
       leave_set I ON O.emp_id = I.emp_id and o.emp_id=1841
   LEFT OUTER JOIN 
       leave_type P ON P.leave_type_id = I.leave_type_id 

我的输出如下所示:

emp_id  leave_title   nod
1841    NULL          NULL
1879    NULL          NULL

我需要如下输出:

emp_id   Leave_title  nod
1841     AL           -
1841     SL           2
1841     CME          -
1842     AL           -
1842     SL           -
1842     CME          -

我需要所有 leave_titlenod 的每个员工是否申请 leave_set

我认为您需要 cross joinleave_type,因为您需要所有组合。后跟 left join 实际休假记录,例如

select O.emp_id, P.leave_title, I.leave_type_id, I.nod
from employee O 
cross join leave_type P 
left join leave_set I ON O.emp_id = I.emp_id and I.leave_type_id = P.leave_type_id
where o.emp_id = 1841

PS:您通常会在 where 子句中限制为相关员工,而不是 join

enter image description here

select em.emp_id,lt.leave_title,ls.nod 来自 leave_type lt cross join employee em left join leave_set ls on ls.leave_type_id=lt.leave_type_id

我假设员工可以多次使用相同的休假类型。

如果是这样,您可能真的想要聚合查询:

select e.emp_id, lt.leave_title, 
       sum(ls.nod) as nod
from employee e cross join
     leave_type lt left join
     leave_set ls
     on ls.emp_id = e.emp_id and
        ls.leave_type_id = lt.leave_type_id
group by e.emp_id, lt.leave_title
order by e.emp_id, lt.leave_title;