2013-02-05 55 views
0

更新table1的我有2个表:SQL:基于查找匹配于另一个表2

表1:

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

column1的和列2是与在栏3和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号来更新表1中的每一行。所得到的表1看起来应该像下面这样:

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

我曾尝试使用选择,其中的各种组合和选择替换(我用的替换,因为包含动物名称的字段有空格它们)。例如,我尝试了以下内容:

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. 

我感谢你的帮助。谢谢。

+0

如果动物名称空间是一致的,我的意思是,如果他们在表1中的同一个地方空格作为表2中,比你不应该需要带他们为了得到一场比赛。你不需要对他们做任何事情。在上面的例子中,你“喜欢”与做等号没什么不同,因为无论如何你在字符串中都没有通配符。除此之外,我认为JohnZ给出了正确的解决方案。 – Jay

回答

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

我认为当你设置column2id时,你的意思是以“where column2 = table1.column4”结束,但是,这就是主意。 – Jay

+0

是的,更新了我的答案。 – JohnZ

+0

@JohnZ - 非常感谢! :) – codingknob

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 
0

enter image description here

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

相关问题