首页 > 解决方案 > 批量 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;

有没有办法可以批量处理?

标签: mysqlsqldatabase

解决方案


使用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


推荐阅读