简体   繁体   English

如何优化更新查询的性能?

[英]How to optimize performance of update query?

I'm trying to optimize the performance of the following update query:我正在尝试优化以下更新查询的性能:

UPDATE a
 SET a.[qty] =
      (
       SELECT MAX(b.[qty])
       FROM [TableA] AS b
       WHERE b.[ID] = a.[ID]
         AND b.[Date] = a.[Date]
         AND b.[qty] <> 0
      )
 FROM [TableA] a
 WHERE a.[qty] = 0
  AND a.[status] = 'New'

It deals with a large table with over 200m.它处理一张超过 200m 的大桌子。 rows.行。

I've already tried to create an index on [qty,status], but it was not really helpfull due to the index update at the end.我已经尝试在 [qty,status] 上创建一个索引,但由于最后的索引更新,它并不是很有帮助。 Generally it is not so easy to create indexes on this table, cause there are a lot other update/insert-queries.一般来说,在这个表上创建索引并不是那么容易,因为还有很多其他的更新/插入查询。 So I'm think to reorganize this query somehow.所以我想以某种方式重新组织这个查询。 Any ideas?有任何想法吗?

TableA is a heap like this: TableA 是这样一个堆:

CREATE TABLE TableA (
    ID            INTEGER       null,
    qty           INTEGER       null,
    date          date          null,
    status        VARCHAR(50)   null,
);

Execution plan: https://www.brentozar.com/pastetheplan/?id=S1KLUWO15执行计划: https://www.brentozar.com/pastetheplan/?id=S1KLUWO15

It's difficult to answer without seeing execution plans and table definitions, but you can avoid self-joining by using an updatable CTE/derived table with window functions没有看到执行计划和表定义很难回答,但您可以通过使用具有 window 函数的可更新 CTE/派生表来避免自连接

UPDATE a
SET
  qty = a.maxQty
FROM (
    SELECT *,
      MAX(CASE WHEN a.qty <> 0 THEN a.qty END) OVER (PARTITION BY a.ID, a.Date) AS maxQty
    FROM [TableA] a
) a
WHERE a.qty = 0
  AND a.status = 'New';

To support this query, you will need the following index要支持此查询,您将需要以下索引

TableA (ID, Date) INCLUDE (qty, status)

The two key columns can be in either order, and if you do a clustered index then the INCLUDE columns are included automatically.两个键列可以按任意顺序排列,如果您执行聚簇索引,则INCLUDE列会自动包含在内。

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

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