内部联接 - 多个表

时间:2015-11-29 19:49:28

标签: sql sql-server

我试图编写一个代码,将3个表中的信息连接在一起,然后将它与一个"大表"进行比较。并根据比较更新测试表中的字段。看一下这个例子:

大表:

    Employee_Id  status 
       2322         5
        222         3
        545         6
       4532         2

表1:

S_Id  status 
2322    7

表2:

S_Id  status 
222     3 

表3:

S_Id  status
545     6 
4532    3

测试表:

TE_Id  IsNotGood
2322      1 
4532      1
222       0
545       0

id" 2322"获得1,因为表1中的状态与大表中的状态不同,4532中的状态相同。

我开始写这个:

update Test Table
set isNotGood = 0
 with ids as (
    select distinct Employee_Id from (
    select Employee_Id,Status from  BigTable as B
    )  as T
    inner join table1 as W on W.S_ID = T.Employee_Id
    inner join table2 as K on K.S_ID = T.Employee_Id
    inner join table3 as R on R.S_ID = T.Employee_Id    
    )

我很高兴您提供完成此查询的提示。

非常感谢!

1 个答案:

答案 0 :(得分:0)

除非employee_id在所有表中,否则您将无法使用内部联接。

UPDATE Test
SET isNotGood = 1
WHERE te_id in (select employee_id
from [Big Table] bt
left join table1 as W on W.s_id = bt.employee_Id
left join table2 as K on K.s_id = bt.employee_Id
left join table3 as R on R.s_id = bt.employee_Id
where (bt.status <> W.status and W.status is not null) or (bt.status <> K.status and k.status is not null) or (bt.status <> R.status and R.status is not null);