在sqlserver中加入3个非常复杂的表

时间:2012-04-08 22:59:39

标签: sql-server join inner-join

 i have 3 tables (employee,structure,District)

 1_employee table contains  empid,workid  and actuallwork  fks to structid 
 2_ structure table contains structid , districtId fk to district
 3_District table contains districtid , districtname

我想要

empid  ,  work 

,actuallwork(来自外键活动的地区名称)

1 个答案:

答案 0 :(得分:1)

您可以在查询中多次使用同一个表,前提是您为每个匹配项提供了不同的别名。结构和区域列出两次,第一次作为工作/区域,第二次作为实际工作/实际区域。这就是在处理对同一个表的多个引用时列的来源的区别。

select employee.empid,
       district.districtname,
       actualdistrict.districtname acturaldistrictname
  from employee
    inner join structure work
       on employee.workid = work.structid
    inner join district
       on work.districtfk = district.districtid
    inner join structure actualwork
       on employee.actuallworkfk = actualwork.structid
    inner join district actualdistrict
       on actualwork.districtfk = actualdistrict.districtid