我有两张桌子;一个很少更新的查找表,以及一个经常更新的数据表。
查找表如下所示,其中Code1和Code2的组合对于每一行都是唯一的。
Code1 | Code2 | Classification
------------------------------
AB | CD | Class1
XX | YY | Class2
数据表看起来像这样;
SomeData | Code1 | Code2 | Classification
------------------------------
foo |AB | CD |
bar |XX | YY |
我需要使用与查找表中Code1和Code2的唯一组合相对应的Classification动态更新数据表。
实现这一目标的最简单/最优雅的方法是什么?
答案 0 :(得分:2)
你只需要加入这两个表:
Select b.SomeData, b.Code1, b.Code2, a.Classification
FROM
Lookup_table a
left join
Data_table b
on (a.Code1 = b.Code1 and a.Code2 = b.Code2)
所以你的更新成为:
Update b
Set b.Classification = a.Classification
FROM
Data_table b
Right join
Lookup_table a
on (a.Code1 = b.Code1 and a.Code2 = b.Code2)
答案 1 :(得分:2)
您可以使用此代码创建视图,并随时获取
select t2.somedata,t1.Code1,t1.Code2,t1.Classification from lookup_table as t1
left join data_table as t2 on t1.code1=t2.code1 and t1.code2=t2.code2
如果您仍需要更新,请使用此
update t2
set
t2.Classification=t2.Classification
from lookup_table as t1
inner join data_table as t2 on t1.code1=t2.code1 and t1.code2=t2.code2
答案 2 :(得分:1)
您可以像这样更新2个表
UPDATE table1, table2
SET table2.Classification = table1.Classification
WHERE table1.Code2 = table2.Code2 AND table1.Code1 = table2.Code1;