从表b更新表a(条件)

时间:2010-01-28 23:01:37

标签: sql sql-server tsql sql-update

晚上好,

实际上,现在是晚上。晚上11点左右。我的大脑正在关闭,我需要一点帮助才能完成并回家:)

我有两张桌子 - 桌子a和桌子b。 当另外两个字段匹配时,我需要使用表b中字段的值更新表a中的字段。这些表没有每条记录的唯一ID:(

基本上,我想这样做:

update a
set importantField = 
(select b.importantfield
from b
where a.matchfield = b.matchfield
and a.matchfield2 = b.matchfield2
)
where a.matchfield = b.matchfield
and a.matchfield2 = b.matchfield2

或者至少......我认为这就是我想做的......

有人可以帮帮我吗?

2 个答案:

答案 0 :(得分:13)

您可以通过更新中的联接来执行此操作:

Update a
Set a.importantField = b.importantField
From a Join b 
  On a.matchfield = b.matchfield
  And a.matchfield2 = b.matchfield2

答案 1 :(得分:3)

使用:

UPDATE TABLE_A
   SET importantField = (SELECT b.importantfield
                           FROM TABLE_B b
                          WHERE b.matchfield = matchfield
                            AND b.matchfield2 = matchfield2) 

SQL Server不支持正在更新的表上的表别名,但上面是一个相关查询 - 那些没有附加表别名b的字段将提供来自TABLE_A的值,因为它没有'有一个别名。

除此之外唯一的问题是,对于具有与TABLE_A匹配的记录的记录,有多个b.importantfield值。使用:

UPDATE TABLE_A
   SET importantField = (SELECT TOP 1 
                                b.importantfield
                           FROM TABLE_B b
                          WHERE b.matchfield = matchfield
                            AND b.matchfield2 = matchfield2) 

..但您也应该使用ORDER BY,否则您将获得任意值b.importantfield

相关问题