When modifying two related tables, take the latest data in one of the tables

update 
a 
set 
a.newid=b.id 
from 
test1  as a 
left join 
(select sfz,max(id)  from test2 group by sfz) as b  on 
test1.sfz= test2.sfz 

When I was writing SQL today, I encountered a problem. When I associated the id of the main table to the sub-table according to the ID card,

When the data of the sub-table is assigned according to the ID card, it is found that there are multiple pieces of data in the database for the same ID card,

Some of the early data are incomplete. To solve this problem, choose to get the largest id in the subtable to ensure that the latest data is obtained

Guess you like

Origin blog.csdn.net/weixin_47035997/article/details/127235930