简体   繁体   English

使用TOP与自我加入进行更新

[英]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 然后,我想在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 . 不需要jointop

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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