SQL Server使用另一个表中的值更新和替换值

时间:2017-10-05 09:14:09

标签: sql sql-server

我有两张桌子:

连接

id  user_id  connection_info
------------------------------
 1    1      ...
 2    1      ...
 3    2      ...

解释

id  connection_id  name
-----------------------
1        1         ...
2        2         ...
3        1         ...

我目前在user_id列中有lists.connection_id个帖子。我想将lists表加入connections connections.user_id = lists.connection_id表,然后将lists.connection_id替换为connections表中的相应ID。

1 个答案:

答案 0 :(得分:1)

您可以像这样使用UPDATE FROM

update l
set l.connection_id = c.id 
from connections c join lists l on c.user_id = l.connection_id

最初,您需要测试要更新的内容,运行SELECT语句:

select l.connection_id as con_old
     , c.id as con_new
     , ... (other cols you might want to check)
from connections c join lists l on c.user_id = l.connection_id