sql - 从列中的值不为空的 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。
解决方案
尝试这个
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
为空则更新
推荐阅读
- javascript - 如果只有一个线程可用,异步/等待有什么好处?
- node.js - Node.js 使用 XMLHttpRequest POST 404 错误
- css - 即使我不包括在内,也会应用 Google 字体粗细
- reactjs - 在 Heroku 上部署时,图像未在 React 应用程序中加载
- objective-c - 如果没有返回语句的 Obj-C 方法包含 @try @catch 块,则它会编译
- c++ - 在查找大输入的数字总和时出错?
- android - 离子构建 --verbose android 错误 ts2740
- reactjs - 反应如何在点击后将 onclick 切换为 false?
- ruby - 我可以在 Ruby 中将一个局部变量命名为“$name”,但它不会成为全局变量吗?
- python - 如何在 Python 中更新来自 DynamoDB 的最新数据条目?