我需要从下表(table1)中获取在同一日期加入(joining_date)部门 dept1 和 dept2 的 emp_id。
emp_id|| department|| joining_date
1 || dept3 || 01/01/2014
1 || dept2 || 01/01/2015
1 || dept1 || 01/01/2015
2 || dept1 || 01/01/2015
2 || dept2 || 01/03/2015
3 || dept1 || 01/02/2015
3 || dept2 || 01/02/2015
3 || dept3 || 01/02/2015
4 || dept1 || 01/01/2014
4 || dept2 || 01/01/2014
5 || dept1 || 01/01/2014
5 || dept2 || 01/01/2015
5 || dept3 || 01/01/2016
6 || dept1 || 01/01/2014
6 || dept2 || 01/01/2014
所以,我应该得到 1,3,4 和 6。
最佳答案
在同一个表上使用 INNER JOIN。
SELECT `first`.* FROM table1 AS first
INNER JOIN table1 AS `second`
ON `first`.emp_id = `second`.emp_id
AND `second`.department = "dept2"
AND `second`.joining_date = `first`.joining_date
WHERE first.department = "dept1"
以 dept2 为例,您必须添加 dept3
关于mysql - 以下场景需要 SQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37803475/