Postgres中的批量更新

时间:2015-07-08 10:43:21

标签: sql postgresql bulkupdate

我需要根据另一个表记录更新一个表记录。

我试过

update      currencies
set         priority_order= t2.priority_order
from        currencies t1
inner join  currencies1 t2
on          t1.id = t2.id

但是给出错误(MySQL和SQL Server的查询工作相同)。

然后我在下面尝试了:

update      currencies
set         priority_order= (select 
                            priority_order 
                            from currencies1 
                            where 
                            currencies.id=currencies1.id
                           )

它工作但很慢,我也需要为一些大桌子做这件事。

有什么想法吗?

2 个答案:

答案 0 :(得分:2)

在Postgres中,这看起来像是:

update currencies t1
    set priority_order = t2.priority_order
    from currencies1 t2
    where t1.id = t2.id;

答案 1 :(得分:1)

UPDATE currencies dst
   SET priority_order = src.priority_order
  FROM currencies src
 WHERE dst.id = src.id
   -- Suppress updates if the value does not actually change
   -- This will avoid creation of row-versions
   -- which will need to be cleaned up afterwards, by (auto)vacuum.
AND  dst.priority_order IS DISTINCT FROM src.priority_order
        ;

测试(10K行,在缓存预热后),对源和目标使用相同的表进行更新:

CREATE TABLE
INSERT 0 10000
VACUUM
Timing is on.
cache warming:
UPDATE 0
Time: 16,410 ms
zero-rows-touched:
UPDATE 0
Time: 8,520 ms
all-rows-touched:
UPDATE 10000
Time: 84,375 ms

通常情况下,您很少会看到没有行影响的情况,也不会影响所有行的情况。但是只触摸了50%的行,查询的速度仍然是原来的两倍。 (加上查询后减少的真空工作)