简体   繁体   English

条件使用LEFT JOIN从查询中排除行

[英]Condition excludes rows from query with LEFT JOIN

I have a statement that I am trying to use to retrieve a complete list of employees, and then their holidays. 我有一个声明,我试图用来检索完整的员工列表,然后是他们的假期。 I would like to keep the employees even if they do not have holidays. 即使他们没有假期,我也想留住员工。 This is my statement so far; 这是我到目前为止的发言;

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"

It is the AND ew.ew_from = ? 这是AND ew.ew_from = ? that removes the employees that do not have holidays stored in the empwork table. 这将删除没有存储在empwork表中的假期的员工。 How can I keep all the people in the employees table that have the department ID I want even if they have no holidays in the empwork table? 即使在empwork表中没有假期,如何让员工表中的所有人员都拥有我想要的部门ID?

Your where clause turns your left join s into inner join s. 您的where子句将left join转换为inner join Put the conditions into the on clause of your joins. 将条件放入联接的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

Conditions on the right table of a LEFT JOIN should be specified only inside the ON clause . 应该仅在ON子句内指定LEFT JOIN 表上的条件。 When they aren't , the join automatically transfer into an INNER JOIN due to NULL comparison: 如果不是,则由于NULL比较,连接会自动转换为INNER JOIN

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"

If I understand the question well this may work: 如果我理解这个问题,这可能有效:

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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM