SQL-如果值存在于2个不同的表中,如何更新表?

时间:2017-09-15 08:10:20

标签: sql sql-server reference inner-join multiple-tables

如果值存在于2个不同的表中,我一直在试图弄清楚如何创建SQL查询以更新主表?

示例:

Table1 (Main)
Employee Number
Name
First Name
Document Name
Filename
Original fileName
DL_Status

Table 2 (list table)
Employee Number
Document Name
Original Filename

Table 3(DIR list)
Original fileName
created
extension file name

输出: DL_Status应该标记为“已完成”,只有当表3中存在原始文件名时,才会从table2条目填充原始fileName?

3 个答案:

答案 0 :(得分:0)

您可以在Table2和table3上应用join,然后编写脚本以将数据更新到主表 注意:如果清楚地提到数据,答案将更加具体。

答案 1 :(得分:0)

尝试这样的事情:

update table1 
set dl_status = a.dl_status,
Original_Filename =a.Original_Filename  
from
(select t2.Employee Number, 'Completed' as dl_status,t2.Original_Filename  
from table2  t2,table3  t3
where t2.Original_Filename= t3.Original_Filename) a
where a.Employee Number = table1.Employee Number

答案 2 :(得分:0)

最有可能

UPDATE m
SET [DL_Status] ='Completed', 
    [Original fileName] = f.[Original fileName]
FROM [Main] m
JOIN [list table] l ON l.[Employee Number] = m.[Employee Number] AND l.[Document Name] = m.[Document Name]
JOIN [DIR list] f ON l.[Original fileName] = f.[Original fileName]
-- optionally
WHERE m.[DL_Status] <> 'Completed' OR m.[Original fileName] <> f.[Original fileName]