MySQL:从另一个 table 更新一个 table 中的 id 值
MySQL: Updating id value in one table from another table
我有一个 table 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行
我还有一个 table 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
在两个 table 中都匹配,那么我想更新两个 table,这样 table2.o_id = table1.o_id
和 table1.b_id = table2.id
update table1
set b_id = table2.id
where ip = table2.ip
这里我想从第一个 table 中的 o_id
更新第二个 table 中的 o_id
。
我还想更新第一个 table 中的 b_id
从第二个 table 中的 id
。
以上查询是否正确?有没有办法在单个查询中更新两个 table?
正在看你的要求
你可以使用 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 .. 这是不可能的(对我来说没有意义)
如果您需要在第一个 table 中从第二个 table 中的 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
您根本不需要更新!首先是能够根据 IP 地址字段正确(并且有意义地)更新 ref ID,这将要求 IP 地址在两个表中都是唯一的。因此,如果它是唯一的,您无论如何都可以使用它来连接表,并从每个表中获取 ID。所以当你可以通过简单地连接表来获取它时就不需要存储它了。
我有一个 table 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行
我还有一个 table 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
在两个 table 中都匹配,那么我想更新两个 table,这样 table2.o_id = table1.o_id
和 table1.b_id = table2.id
update table1
set b_id = table2.id
where ip = table2.ip
这里我想从第一个 table 中的 o_id
更新第二个 table 中的 o_id
。
我还想更新第一个 table 中的 b_id
从第二个 table 中的 id
。
以上查询是否正确?有没有办法在单个查询中更新两个 table?
正在看你的要求 你可以使用 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 .. 这是不可能的(对我来说没有意义)
如果您需要在第一个 table 中从第二个 table 中的 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
您根本不需要更新!首先是能够根据 IP 地址字段正确(并且有意义地)更新 ref ID,这将要求 IP 地址在两个表中都是唯一的。因此,如果它是唯一的,您无论如何都可以使用它来连接表,并从每个表中获取 ID。所以当你可以通过简单地连接表来获取它时就不需要存储它了。