简体   繁体   中英

Update using TOP versus self-join

What is more efficient when updating a table based off the minimum value of a foreign key?

In this instance, I will be removing the row with the flag set. I then want to set the flag on the row with the smallest fk_id

Table Layout:

+----+------------+-----------+------------+
| id | fk_id      | fk_id2    | some_flag  |
+----+------------+-----------+------------+
|  1 | 21         | 1010101   |          1 |
|  2 | 22         | 1010101   |          0 |
|  3 | 23         | 1010101   |          0 |
|  4 | 24         | 1010101   |          0 |
+----+------------+-----------+------------+

My approach has been to join the table on itself using the following

Update t1
set some_flag = 1
From TableA t1
Left Join TableA t2
on t1.fk_id2 = t2.fk_id2 AND t1.fk_id > t2.fk_id
where t1.fk_id2 = 1010101 AND t2.fk_id2 IS NULL

I feel like this isn't efficient and there has to be a better way.

Thought about updating based off a select statement, but perhaps that isn't better. I assume my solution is worse for tables with lots of fields.

Use window functions:

with toupdate as (
      select a.*, row_number() over (partition by fk_id2 order by fk_id) as seqnum
      from table a
     )
update toupdate
    set some_flag = 1
    where seqnum = 1;

There is no need for either a join or top .

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