简体   繁体   中英

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 = ? that removes the employees that do not have holidays stored in the empwork table. 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?

Your where clause turns your left join s into inner join s. Put the conditions into the on clause of your joins.

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 . When they aren't , the join automatically transfer into an INNER JOIN due to NULL comparison:

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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