【问题标题】:Update table a columns using columns from table b (values of 2 columns of table b need to taken from table c)使用表 b 中的列更新表 a 列(表 b 的 2 列的值需要从表 c 中获取)
【发布时间】:2014-05-10 19:53:38
【问题描述】:

我需要通过表 b 列 col3、col4、col5 和 col6 更新表 A 列 col3、col4、col5 和 col6,但是表 b col5 和 col6 值需要来自表 c col1。 意味着表 b col5 和 col6 中有值但是我需要用表 c col1 中的值替换它们,并且需要相应地更新表 a col5 和 col6。 表 a 和表 b 具有共同的 col1 和 col2。我正在尝试这样的事情。

Update a
a.col3 = b.col3,  
a.col4 = b.col4,
a.col5 = (select col1 from table_c c where c.col2=b.col5),
a.col6 = (select col1 from table_c c where c.col2=b.col6)
from table_A a inner join table_b
on  a.col1=b.col1 and a.col2=b.col2

有人可以帮我重新构建上面的更新查询吗? 提前感谢您的帮助。

【问题讨论】:

  • 能否也放样例数据(更新前是什么,更新后是什么)?
  • @TTeeple: table a abc def 0 0 -999 -999 table b abc def 1 1 -sa1283 -sa4958 table c -sa1283 1234 -sa4958 3456 更新后table A应该是这个table a abc def 1 1 1234 3456 希望这会更清楚 -

标签: sql-server


【解决方案1】:

Update a a.col3 = b.col3, a.col4 = b.col4, a.col5 = c.col1, a.col6 = d.col1 from table_A a inner join table_b on a.col1=b.col1 and a.col2=b.col2 inner join table_c c on c.col2 = b.col5 inner join table_c d on d.col2 = b.col6

否则,在子查询中使用select top 1

【讨论】:

  • 嗨,当我使用内部查询时,它会为表 a 中的每一行返回重复行。
猜你喜欢
  • 1970-01-01
  • 2021-06-06
  • 1970-01-01
  • 2016-03-17
  • 2021-06-27
  • 1970-01-01
  • 2021-12-01
  • 1970-01-01
  • 2020-02-19
相关资源
最近更新 更多