首页 > 解决方案 > 从列中的值不为空的 self 表更新表

问题描述

我有一个包含值的表:

dbid    name         userid
------------------------------
154     xyz          NULL
987     xyz          NULL
777     xyz          5
111     abc          NULL
745     abc          NULL
748     abc          6

预期输出:

dbid     name     userid
------------------------------
154     xyz          5
987     xyz          5
777     xyz          5
111     abc          6
745     abc          6
748     abc          6

除了一对一名称之外,用户标识列中的所有值均为空值。我想为 name = 'xyz' 的所有行在用户 ID 中设置 5。同样,要更新表以在 userid where name = 'abc' 中设置 6。

对于上述场景,更新表的查询应该是什么?

注意:以上只是一个例子。我有一个包含数十万条记录的表。我不能在查询中写 id 5 或 6。

标签: sqlsql-servertsqlsql-update

解决方案


尝试这个

update table_name 
   set table_name.userid = (
        select top(1) ss.userid 
          from table_name ss 
         where ss.name = table_name.name 
           and ss.userid is not null
        ) 
    where table_name.userid is null

此查询正在搜索userid名称相同的第一条记录,如果userid为空则更新


推荐阅读