SQL batch update update nested select update

overview

There are two tables [ user ] and [ city ], the user table city_uuidand city_nothe city table city_uuidare city_noin one-to-one correspondence, but the user table only has one city_uuid. At this time, the corresponding citycity_no needs to be updated in batches to the user table
insert image description here
insert image description here

Batch update method

The first way (inner join)

update u
set u.city_no = c.city_no
from user u 
inner join city c 
on u.city_uuid = c.city_uuid
where u.city_uuid is not null and u.city_no is null

Second way (subquery)

update u
set u.city_no = (select c.city_no from city c where u.city_uuid = c.city_uuid)
from user u

The third way: (Cartesian product)

update u
set u.city_no = c.city_no  
from [user] u, city c 
where u.city_uuid = c.city_uuid

update Multi-table update

update table1 t1,table2 t2, table3 t3, ... , tablen tn
set t1.column= ?, t2.column, t3.column = ?, ... , tn.column = ?
where t1.xx= ?, t2.xx = ?, ... , tn.xx = ?

Case: (conditionUuid is the foreign key of the user table, each conditionUuid corresponds to two user records, and the product record is overwritten with the specified field value of the consumer record)

update r2
set r2.userUuid = r1.userUuid, r2.userName = r1.userName , r2.age = r1.age, r2.updatedTime = '2021-02-22 22:22:22.222'
from user r1
inner join user r2
on r1.conditionUuid = r2.conditionUuid
where r1.conditionValue = 'condition-consumer-00000000000000000' and r1.userName is not null
and r2.conditionValue = 'condition-producter-0000000000000000' and r2.userName is not null

Guess you like

Origin blog.csdn.net/qq_40542534/article/details/117367096