【问题标题】:Speed up simple update statement in postgres for 1 million rows为 100 万行加速 postgres 中的简单更新语句
【发布时间】:2017-11-02 08:20:48
【问题描述】:

我在 postgres 中有一个非常简单的 sql update 语句。

UPDATE p2sa.observation SET file_path = replace(file_path, 'path/sps', 'newpath/p2s')

观察表有 1513128 行。到目前为止,查询已经运行了大约 18 个小时,还看不到尽头。

file_path 列未编入索引,因此我猜它正在执行从上到下的扫描,但时间似乎有点过长。可能替换也是一个缓慢的操作。

是否有一些替代或更好的方法来进行这种影响所有行的一次性更新。它本质上是将旧文件路径更新到新位置。它只需要更新一次或将来可能再次更新。

谢谢。

【问题讨论】:

  • 这似乎真的很长一段时间。你查过是不是waiting for a lock
  • 每一行都有'path/sps'吗?如果没有,您可以添加一个 where file_path 像 '%path/sps%'。

标签: sql postgresql performance sql-update


【解决方案1】:

在 SQL 中,您可以执行一个 while 循环来批量更新。

试试这个看看效果如何。

Declare @counter int 
Declare @RowsEffected int 
Declare @RowsCnt int 
Declare @CodeId int 
Declare @Err int
DECLARE @MaxNumber int = (select COUNT(*) from p2sa.observation)
SELECT @COUNTER = 1
SELECT @RowsEffected = 0


WHILE ( @RowsEffected < @MaxNumber)
BEGIN 
SET ROWCOUNT 10000


UPDATE p2sa.observation 
SET file_path = replace(file_path, 'path/sps', 'newpath/p2s')
where file_path != 'newpath/p2s'

SELECT @RowsCnt = @@ROWCOUNT ,@Err = @@error 
IF @Err <> 0 
BEGIN 
Print 'Problem Updating the records' 
BREAK
END 
ELSE 

SELECT @RowsEffected = @RowsEffected + @RowsCnt 
PRINT 'The total number of rows effected :'+convert(varchar,@RowsEffected) 

            /*delaying the Loop for 10 secs , so that Update is completed*/    

     WAITFOR DELAY '00:00:10'         
 END
 SET ROWCOUNT 0

【讨论】:

  • 如您所见,它等待 10 秒,因此可以确定行已更新,您可以根据所见调整此时间或行数。如果您有 10.000 行并等待 10 秒,您的执行时间将约为 25 分钟。
猜你喜欢
  • 2021-10-08
  • 2021-08-02
  • 2021-04-06
  • 1970-01-01
  • 1970-01-01
  • 2011-03-22
  • 1970-01-01
  • 2014-03-29
  • 1970-01-01
相关资源
最近更新 更多