SQL在列上加入两个表

时间:2014-02-26 00:10:17

标签: sql database

Department和Employee有两个表 部:

DID DName           PhoneExt 
ADM Administration  100 
CLT Client Services 101 
DAT Data Conversion 102 

EMPLOYEE
EID EName Salary   MID   DID 
e001 Martin 57000        CLT 
e002 West 39000   e001   CLT 
e003 Wilson 64000        DAT 
e004 Patel 48000  e003   DAT 
e005 Rae 42000    e001   CLT 
e006 Jones 36000  e003   DAT 
e007 Dunn 52000   e003   PRG

如何列出其经理来自客户的员工的姓名和ID 服务部门?

4 个答案:

答案 0 :(得分:2)

列出名称和ID:

SELECT EName, EID

这些员工:

FROM EMPLOYEE

其经理来自:

WHERE MID IN

客户服务部门:

(SELECT EID FROM EMPLOYEE WHERE DID = 'CLT')

答案 1 :(得分:0)

SELECT e1.* FROM employee e1 WHERE e1.MID IN 
  (SELECT e2.EID FROM employee e2 WHERE e2.DID = 'CLT')

答案 2 :(得分:0)

您可以使用此查询:

SELECT EID, EName FROM EMPLOYEE WHERE MID IN (SELECT EID FROM EMPLOYEE WHERE DID = 'CLT')

答案 3 :(得分:0)

使用子查询很好(正如Dour,Mohamed,Rafa等人所建议的那样),但是,通过自行加入employee表,你可以更有效地完成这项工作(没有子查询):

SELECT
   emp.Ename,
   emp.EID
FROM
   EMPLOYEE emp

   INNER JOIN EMPLOYEE mngr
   ON emp.MID = mngr.EID
WHERE
   mngr.DID = 'CLT'

注意 - 您根本不需要使用部门表...