mysql - 批量 SQL 查询以更新不同表中的字段
问题描述
Table t1 - Fields a, b
Table t2 - Fields a, c
(a 是两个表之间的公共字段)
我在 t2 中添加了字段 b 并希望使用 t1 中的引用填充相同的数据
这可以使用以下查询来完成(例如 a = 100, 101, ...)
update t2 set b = (select b from t1 where a = 100 limit 1) where a = 100;
update t2 set b = (select b from t1 where a = 101 limit 1) where a = 101;
有没有办法可以批量处理?
解决方案
使用join
:
update t2 join
t1
on t2.a = t1.a
set t2.b = t1.b;
您还可以使用相关子查询:
update t2
set b = (select t1.b from t1 where t1.a = t2.a);
但是,不匹配的值将设置为NULL
。
推荐阅读
- python - 在 ORM 模型类中编写非 ORM 模型代码是否可以接受?
- node.js - 无法使用 ActiveMQ 中的 STOMP 选择器过滤消息
- regex - 替换字符串中除第一次出现之外的元素在Scala中
- python - 尝试从类中的函数调用函数
- java - ${_csrf} 做什么?这是一个隐式 EL 对象吗?
- ionic4 - Ionic 4 - 移除滚动条
- tensorflow - ValueError:没有为任何变量提供渐变,请检查您的图表是否有不支持渐变的操作
- react-native - 渲染项目 | 反应原生
- swift - 将状态栏和导航栏设置为相同颜色
- javascript - 显示 Hover 而不是 Href 进行条件检查