sql:update table1基于另一个table2中的查找匹配

时间:2013-02-05 18:06:56

标签: sql replace matching sql-like

我有两张桌子:

表1:

NULL    NULL    Cat.XX 23   Cow.XX 87
NULL    NULL    Tiger.XX 99 Elephant.XX

Column1和Column2分别是与column3和column4中的值相关联的ID号。

表2:

84048713    Cat.XX 23   Blah1   Blah2   Blah3   Blah4   
44008714    Elephant.XX 77  Blah1   Blah2   Blah3   Blah4   
64038715    Cow.XX 87   Blah1   Blah2   Blah3   Blah4
34058716    Tiger.XX 99 Blah1   Blah2   Blah3   Blah4
74038717    Zebra.XX 34 Blah1   Blah2   Blah3   Blah4
94098719    Whale.XX 47 Blah1   Blah2   Blah3   Blah4

我想用适当的ID号更新table1中的每一行。生成的table1应如下所示:

84048713    64038715    Cat.XX 23   Cow.XX 87
34058716    44008714    Tiger.XX 99 Elephant.XX

我尝试了使用select,where和select replace的各种组合(我使用replace,因为包含动物名称的字段中包含空格)。例如,我尝试了以下内容:

select IDs from table2 where 
(select replace("Name", ' ', '') from table2
LIKE
(select replace("Name", ' ', '') from table1)

但是我收到以下错误:

Msg 512, Level 16, State 1, Line 1
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

感谢您的帮助。谢谢。

3 个答案:

答案 0 :(得分:1)

update table1 set Column1ID = (select ID from table2 where column2 = table1.column3),Column2ID = (select ID from table2 where column2 = table1.column4)

答案 1 :(得分:1)

试试这个;

Update t1
Set t1.col1 = case t1.col3 when t2.col2 then t2.col1 else t1.col1, 
    t1.col2 = case t1.col4 when t2.col2 then t2.col1 else t1.col2
From table1 t1 join table2 t2 
    on t1.col3 = t2.col2 or t1.col4 = t2.col2

答案 2 :(得分:0)

enter image description here

  

UPDATE TABLE_1 SET ID = B.ID,ID2 = C.ID FROM TABLE_1左下角   OUTER JOIN TABLE_2 AS B ON A.TEMPID = B.TEMPID LEFT OUTER JOIN TABLE_2   AS C ON A.TEMPUD2 = C.TEMPID