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
默认情况下,employee
表termination_id
设置为NULL
。如果员工被终止,则id
表中的termination
被设置为值。我想让所有在某个日期之前没有被终止或终止的员工。
上述查询会获得所有结果,包括termination_date
小于2016-01-01的结果。是否可以修改查询,以便省略termination_date
小于2016-01-01的结果?或者我是否必须执行2个不同的查询并合并结果才能实现此目的。
注意避免混淆:我希望员工仍在工作(未被终止)且未在2016-01-01之前被终止
答案 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