我有一个表 table1
o_id
作为 PK
, ipaddress
, b_id
o_id ip b_id
9205 10.10.10.10 null
9206 10.10.10.11 null
9207 10.10.10.12 null
---超过1000行
我有另一个表 table2
id
作为 PK
, ipaddress
, b_id
id ip o_id
18356 10.10.10.10 null
18357 10.10.10.11 null
18358 10.10.10.12 null
---超过1000行
现在,如果 ipaddress
在两个表中都匹配,那么我想更新两个表,使得 table2.o_id = table1.o_id
和 table1.b_id =表2.id
update table1
set b_id = table2.id
where ip = table2.ip
在这里,我想从第一个表中的 o_id
更新第二个表中的 o_id
。
我还想从第二个表中的 id
更新第一个表中的 b_id
。
以上查询是否正确?有没有办法在单个查询中更新两个表?
最佳答案
也在看你的要求 你可以使用 update with join
update table1 t1
inner join table2 t2 on t1.ip = t2.ip
set t1.o_id = t2.o_id,
t1.b_id = t2-id
但是查看您的数据,您有 table2.o_id = null 所以通过更新您使所有 o_id(主键)为 null .. 这是不可能的(对我来说没有意义)
如果你需要从第二个表中的id更新第一个表中的b_id那么应该是
update table2 t2
inner join table1 t1 on t1.ip = t2.ip
set t2.o_id = t1.o_id,
t2.id = t1.b_id
关于MySQL:从另一个表更新一个表中的id值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48047678/