sql - 如何防止更新语句将某些记录设置为空?
问题描述
我正在尝试使用下面的查询对具有现有表的一个表运行更新。代码列记录需要更新,但只更新其中的一部分。我的查询似乎有效,但任何应该留在代码列中的记录最终都被设置为 NULL。如何修改此查询以保持这些记录不变?
询问
update t1 x
set x.code =
(select code from
(select distinct address, city, prov, aflag, rcode from t2) y
where x.address = y.address and x.city = y.city and x.state = y.state and x.flag = y.flag)
where x.aflag like '%b%';
表 1:要更新的代码
t1
address city state flag code
123 aaa il b 400
567 bbb il b 400
345 bbb il b -500
789 ddd il b 600
546 ccc il b 700
表 2:用于更新 T1 的代码列
t2
address city state flag code
123 aaa il b -555
444 bbb il b -555
345 bbb il b -555
888 kkk il b -555
546 ccc il b -555
What the query currently outputs
current output
address city state flag code
123 aaa il b 400
444 bbb il b NULL
345 bbb il b -500
888 kkk il b NULL
546 ccc il b -700
我希望查询保持与更新表中没有匹配项的记录保持不变,如下所示
What I want
address city state flag code
123 aaa il b 400
444 bbb il b -555
345 bbb il b -500
888 kkk il b -555
546 ccc il b -700
谢谢!
解决方案
最好的方法是exists
在where
子句中使用:
update t1 x
set x.code = (select code
from t2 y
where x.address = y.address and x.city = y.city and x.state = y.state and x.flag = y.flag and rownum = 1
)
where x.aflag like '%b%' and
exists (select code
from t2 y
where x.address = y.address and x.city = y.city and x.state = y.state and x.flag = y.flag and rownum = 1
);
推荐阅读
- python - 如何在 Prometheus 上显示一段时间内访问 Superset 仪表板的用户数?
- reactjs - React 中的 .js、.tsx 和 .jsx 有什么区别?
- firebase - 无法加载 providerinstaller 模块:找不到可接受的模块。本地版本为 0 远程版本为 0 错误颤动
- react-native - ExpressionStatement 预期节点的属性表达式为 ["Expression"] 类型,但得到 "TSModuleBlock"
- python - 如何在不破坏进度条的情况下在未来打印?
- html - 我的 ng-template 标记不等待 ngIf async 完成
- python - 匹配多个列忽略熊猫中的顺序
- php - PHP\Laravel 中的符号链接问题
- processing - 修复使用 image() 时的空指针异常;进行中
- javascript - 将 fetch() 数据保存到数组变量以在另一个外部函数中使用