【问题标题】:sql: update table1 based on lookup match in another table2sql:根据另一个表2中的查找匹配更新表1
【发布时间】:2013-01-20 18:18:15
【问题描述】:

我有 2 张桌子:

表1:

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

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

表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.

感谢您的帮助。谢谢你。

【问题讨论】:

  • 如果动物名称中的空格是一致的,我的意思是,如果它们在 table1 和 table2 中的相同位置有空格,那么您不需要将它们去掉以获得匹配。您不需要对它们做任何事情。您在上面的示例中“喜欢”与执行等号没有什么不同,因为无论如何您在字符串中都没有通配符。除此之外,我认为 JohnZ 给出了正确的解决方案。

标签: sql replace matching sql-like


【解决方案1】:
update table1 set Column1ID = (select ID from table2 where column2 = table1.column3),Column2ID = (select ID from table2 where column2 = table1.column4)

【讨论】:

  • 我认为,当您设置 column2id 时,您的意思是以“where column2=table1.column4”结尾,但是是的,就是这样。
  • @JohnZ - 非常感谢! :)
  • @algotr8der - 没问题,很高兴为您提供帮助
【解决方案2】:

试试这个;

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

【讨论】:

    【解决方案3】:

    更新 TABLE_1 SET ID = B.ID , ID2 = C.ID 从 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

    【讨论】:

      猜你喜欢
      • 2010-09-18
      • 1970-01-01
      • 1970-01-01
      • 2017-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-11
      相关资源
      最近更新 更多