好的,
我有一张桌子上有人(身份证,姓名,地址等)。与表员工(id,person_id,salary,department_id等)有一对多的关系。员工都属于(多对一关系)不同的部门(id,title,location,year_id),这些部门是特定年份的。
我想写一个查询来查找2013年工作的员工,并排除那些在2014年继续为公司工作的员工。基本上我想要那些去年为公司工作的人,但不再这样了。我在下面做了一个微弱的尝试。
SELECT * FROM people
JOIN employees ON people.id=employees.person_id
RIGHT JOIN departments ON employees.department_id=departments.id
AND departments.year_id='2013'
WHERE departments.year_id<>'2014'
任何帮助都将不胜感激。
答案 0 :(得分:0)
您可以使用not exists
检查那些在2014年停止工作的员工
SELECT * FROM people
JOIN employees e ON people.id=e.person_id
RIGHT JOIN departments ON e.department_id=departments.id
WHERE departments.year_id='2013'
AND NOT EXISTS
(SELECT 1
FROM departments
JOIN employees ee ON ee.department_id=departments.id
WHERE departments.year_id = '2014'
AND e.id=ee.id
)
或not in()
解决方案但由于依赖子查询而不推荐使用
SELECT * FROM people
JOIN employees e ON people.id=e.person_id
RIGHT JOIN departments ON e.department_id=departments.id
WHERE departments.year_id='2013'
AND e.id NOT IN
(SELECT ee.id
FROM departments
JOIN employees ee ON ee.department_id=departments.id
WHERE departments.year_id = '2014'
)
答案 1 :(得分:0)
我不确定为什么你有一对一的人员对员工或者如何在你的系统中应用这个功能,但如果我理解正确,这应该有效。
M Khalid Junaid的答案可能会有效,但是我鄙视使用子查询,因为它们不能很好地扩展。以下应该可以正常工作,每个员工只返回1行(没有组),此外它只有1个左连接而没有子查询。
SELECT * FROM people
JOIN employees ON people.id=employees.person_id
JOIN departments as dept_start ON employees.department_id=departments.id && departments.year_id = 2013
LEFT JOIN departments as dept_end ON employees.department_id=departments.id && departments.year_id = 2014
WHERE dept_start.id IS NOT NULL && dept_end.id IS NULL