简体   繁体   中英

UPDATE SELECT with JOIN one-to-many relationship in SQL server

Let's say I have table

A

Col1 Col2
 1    AB
 2    CD

B

Col1 Col2
 1    EF
 1    GH
 2    IJ
 2    KL

If I have following query

UPDATE A
SET Col2 = B.Col2
FROM A
INNER JOIN B ON A.Col1 = B.Col1

I tried this and the result is

A

Col1 Col2
 1    EF
 2    IJ

So, it always update from the first row? Just wanted to make sure the correct behavior because what I'm about to update is quite critical.

There is no such a definition as "First row" or "Last row" when you talk about tables in RDBMS. If you have not specify any order the database engine is free to use any records as First record. There are of course exceptions such as existence of clustered indices, collations etc.

If you do not specify any orders you cannot simply assume what the first record would be.

I suggest you modify your query to use a predefined order of the values you want in your update. Eg if you want to update to a value coming first in alphanumeric order then use this query:

UPDATE A
SET Col2 = B.Col2
FROM A
INNER JOIN 
(
SELECT Col1, Col2,
ROW_NUMBER() OVER(PARTITION BY Col1 ORDER BY Col2) rn
)
B ON A.Col1 = B.Col1 AND b.rn=1

Please note, that when you specifying an order the order can be set by a completely different column. Imagine you have a DateUpdated column and you wish to use the latest value based on the latest DateUpdated event:

UPDATE A
SET Col2 = B.Col2
FROM A
INNER JOIN 
(
SELECT Col1, Col2, DateUpdated,
ROW_NUMBER() OVER(PARTITION BY Col1 ORDER BY DateUpdated DESC) rn
)
B ON A.Col1 = B.Col1 AND b.rn=1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM