如果列中的值不为null,则为MySQL JOIN条件

时间:2016-01-27 06:47:22

标签: mysql join

查询

SELECT employee.emp_number as employee_id,
employee.termination_id,
employee.firstname as user_name,
termination.termination_date 
FROM employee
JOIN user ON user.emp_number = employee.emp_number 
JOIN reportto ON reportto.emp_number = employee.emp_number 
LEFT JOIN termination ON 
( termination.id = employee.termination_id 
  AND termination.termination_date > '2016-01-01') 
WHERE ohrm_user.created_by = '31' 
GROUP BY employee.emp_number

我在尝试什么

默认情况下,employeetermination_id设置为NULL。如果员工被终止,则id表中的termination被设置为值。我想让所有在某个日期之前没有被终止或终止的员工。

上述查询会获得所有结果,包括termination_date小于2016-01-01的结果。是否可以修改查询,以便省略termination_date小于2016-01-01的结果?或者我是否必须执行2个不同的查询并合并结果才能实现此目的。

注意避免混淆:我希望员工仍在工作(未被终止)且未在2016-01-01之前被终止

3 个答案:

答案 0 :(得分:1)

您可以尝试将termination_date上的检查移至WHERE子句:

SELECT employee.emp_number as employee_id, employee.termination_id,
    employee.firstname as user_name, termination.termination_date 
FROM employee
JOIN user
    ON user.emp_number = employee.emp_number 
JOIN reportto
    ON reportto.emp_number = employee.emp_number 
LEFT JOIN termination
    ON termination.id = employee.termination_id 
WHERE (termination.termination_date IS NULL OR termination.termination_date > '2016-01-01')
    AND ohrm_user.created_by = '31'
GROUP BY employee.emp_number

关于WHERE条款的评论:

WHERE (termination.termination_date IS NULL OR termination.termination_date > '2016-01-01')

这将首先检查termination.termination_date是否为NULL,这表示员工记录与termination表不匹配,暗示他仍在工作。其次,如果termination.termination_date不是NULL,则会检查他的终止日期是否发生在2016-01-01之后。

答案 1 :(得分:1)

移动

AND termination.termination_date > '2016-01-01'

从现在位置到之后

WHERE ohrm_user.created_by = '31'

应该做的伎俩

答案 2 :(得分:1)

尝试以下查询 -

SELECT employee.emp_number AS employee_id,
employee.termination_id,
employee.firstname AS user_name,
termination.termination_date 
FROM employee
JOIN USER ON user.emp_number = employee.emp_number 
JOIN reportto ON reportto.emp_number = employee.emp_number 
LEFT JOIN termination ON 
( termination.id = employee.termination_id ) 
WHERE ohrm_user.created_by = '31' 
AND (employee.termination_id IS NULL OR termination.termination_date >= '2016-01-01') 
GROUP BY employee.emp_number