如何在SQL Server中使用JOIN有效地选择嵌套依赖表

时间:2017-02-10 09:53:28

标签: sql sql-server join

我有一个父表"员工",员工信息存储在3个子表中,每个子表有一个子表。请考虑以下表格

表:员工(Level#1)

EmpId    IsActive
__________________
1        1
2        1
3        1
4        0
5        0
6        1

表:EmployeeEmail(Level#2)

EmpEmailId    EmpId    EmailId
______________________________
1             1         1
2             4         3
3             6         4

表:EmailAddress(Level#3)

EmailId    Email
____________________________
1          one@gmail.com
2          two@gmail.com
3          three@gmail.com
4          four@gmail.com

表:EmployeePhone(Level#2)

EmpPhoneId    EmpId    PhoneId
______________________________
1             1         1
2             2         2
3             5         4

表:PhoneNumber(Level#3)

PhoneId    PhoneNumber
_______________________
1          9912345671
2          9912345672
3          9912345673
4          9912345674

现在我需要选择活动员工记录(完整信息),如果员工有电话号码,那么它应该来,否则它应该是NULL,我也需要相同的电子邮件。

请帮助我如何加入这个结构并有效地获取记录?

2 个答案:

答案 0 :(得分:0)

一旦它可以帮助您,请尝试此查询。

 select EMP.EmpId, EMP_ADD.Email,PH_NBR.PhoneNumber 
 from Employee EMP
 LEFT JOIN EmployeeEmail EMP_EM ON EMP.EMP_ID=EmpId
 LEFT JOIN EmailAddress EMP_ADD ON EMP_ADD.EmailId=EMP_EM.EmpEmailId
 LEFT JOIN EmployeePhone EMP_PH ON EMP_PH.EmpId=EMP.EmpId
 LEFT JOIN PhoneNumber PH_NBR ON PH_NBR.PhoneId=EMP_PH.PhoneId
 WHERE EMP.IsActive=1

注意:这里我假设Active为1而Inactive为0.如果是反向则更改,其中EMP.IsActive = 0

(或)尝试这个。我正在尝试分别使用手机和电子邮件数据,然后使用emp_id加入

;with email as 
(
 select EMP.EmpId, EMP_ADD.Email
 from Employee EMP
 LEFT JOIN EmployeeEmail EMP_EM ON EMP.EMP_ID=EmpId
 LEFT JOIN EmailAddress EMP_ADD ON EMP_ADD.EmailId=EMP_EM.EmpEmailId
 WHERE EMP.IsActive=1
 )
 ,Phone as
 (
 select EMP.EmpId,PH_NBR.PhoneNumber 
 from Employee EMP
 LEFT JOIN EmployeePhone EMP_PH ON EMP_PH.EmpId=EMP.EmpId
 LEFT JOIN PhoneNumber PH_NBR ON PH_NBR.PhoneId=EMP_PH.PhoneId
 WHERE EMP.IsActive=1
)
select * from email e
left join Phone p on p.EmpId=e.EmpId

答案 1 :(得分:0)

替代形式:

  • 实际需要的三个表只在主查询中
  • 联结表用于通过ON EXISTS(...)
  • 将它们粘合在一起
SELECT e.empid, em.email, pn.phonenumber
 FROM employee e
 LEFT JOIN emailaddress em 
        ON EXISTS ( -- junctiontable
        SELECT * FROM employeeemail ee
        WHERE ee.empid = e.emp_id
        AND ee.empemailid = em.emailid
        )
 LEFT JOIN phonenumber pn 
        ON EXISTS( -- junctiontable
        SELECT * FROM employeephone ep
        WHERE ep.empid = e.empid
        AND ep.phoneid = pn.phoneid
        )
 WHERE e.isactive=1
        ;