下面的场景需要SQL查询

时间:2016-06-14 05:17:13

标签: mysql sql

我需要从下表(table1)中获取emp_id,该表已在同一日期加入(joined_date)department dept1和dept2。

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&结果就是这样。

2 个答案:

答案 0 :(得分:1)

在同一张桌子上使用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

答案 1 :(得分:-1)

您可以使用自联接来获得结果

select distinct d1.emp_id 
from   dept1 d1, 
       dept2 d2 
where  d1.department = 'dept1' 
and    d2.department = 'dept2' 
and    d1.joining_date = d2.joining_date;
相关问题