条件使用LEFT JOIN

时间:2016-08-10 10:14:11

标签: c# mysql join

我有一个声明,我试图用来检索完整的员工列表,然后是他们的假期。即使他们没有假期,我也想留住员工。这是我到目前为止的陈述;

SELECT emp.em_pplid, emp.em_name
FROM employs emp
LEFT JOIN people ppl ON emp.em_pplid = ppl.pp_id
LEFT JOIN empwork ew ON emp.em_pplid = ew.ew_pplid
WHERE emp.em_deptid = ?
AND ppl.pp_employee = ?
AND emp.em_type < ?
AND ew.ew_from > ?
ORDER BY emp.em_name"

AND ew.ew_from = ?删除了empwork表中没有假期的员工。即使在empwork表中没有假期,如何让员工表中的所有人都拥有我想要的部门ID?

3 个答案:

答案 0 :(得分:0)

您的where子句会将left join转换为inner join s。将条件放入联接的on子句中。

SELECT emp.em_pplid, emp.em_name
FROM employs emp
LEFT JOIN people ppl ON emp.em_pplid = ppl.pp_id                        
LEFT JOIN empwork ew ON emp.em_pplid = ew.ew_pplid
                    AND ew.ew_from > ?
WHERE emp.em_deptid = ?
AND emp.em_type < ?
AND (ppl.pp_employee IS NULL OR ppl.pp_employee = ?)
ORDER BY emp.em_name

答案 1 :(得分:0)

只应在LEFT JOIN子句中指定ON表的条件。如果不是,则由于INNER JOIN比较,加入会自动转移到NULL

SELECT emp.em_pplid, emp.em_name
FROM employs emp
LEFT JOIN people ppl
 ON emp.em_pplid = ppl.pp_id AND ppl.pp_employee = ?
LEFT JOIN empwork ew 
 ON emp.em_pplid = ew.ew_pplid AND ew.ew_from > ?
WHERE emp.em_deptid = ?
AND emp.em_type < ?
ORDER BY emp.em_name"

答案 2 :(得分:0)

如果我理解这个问题,这可能有用:

SELECT emp.em_pplid, emp.em_name
FROM employs emp
LEFT JOIN people ppl ON emp.em_pplid = ppl.pp_id
LEFT JOIN empwork ew ON emp.em_pplid = ew.ew_pplid
WHERE emp.em_deptid = ?
AND ppl.pp_employee = ?
AND emp.em_type < ?
AND (ew.ew_from > ? OR ew.ew_from IS NULL)
ORDER BY emp.em_name"