Select employees belong to both department in database

时间:2017-09-16 11:00:07

标签: mysql sql

I have a table

 EmpName   DeptID
-------------------------
   Sam        1
   John       2
   Sam        2
   Bill       3
   Mary       1

I want to select employees who belong to both DeptID '1' and DeptID '2' For this table i want to show EmpID : sam
How can i write a query in MySql

Thanks in advance.

4 个答案:

答案 0 :(得分:1)

使用sum

的另一种方法
select EmpName
from demo
group by EmpName
having sum(DeptID = 1) 
and sum(DeptID = 2) 

DEMO

答案 1 :(得分:0)

HAVINGGROUP BY一起使用。

<强>查询

select EmpName from your_table_name
where DeptID in (1,2)
group by EmpName 
having count(distinct DeptID) = 2;

答案 2 :(得分:0)

您可以在过滤行

上使用having子句
  select empname 
  from my_table
  where dempId in (1,2)
  group by empname
  having count(distinct DeptID) = 2

答案 3 :(得分:0)

使用自联接的另一种方法

mvn clean install --projects :proj1,:then-proj2