簡體   English   中英

在大表上使用連接更新 - 性能提示?

[英]Update using join on big table - performance tips?

一直在為這個更新而苦苦掙扎,永遠不會完成

update votings v
set voter_id = (select pv.number from voters pv WHERE pv.person_id = v.person_id);

當前表有 96M 條記錄

select count(0) from votings;
  count   
----------
 96575239
(1 registro)

更新顯然正在使用索引

explain update votings v                             
set voter_id = (select pv.number from voters pv WHERE pv.rl_person_id = v.person_id);
                                                    QUERY PLAN                                                     
-------------------------------------------------------------------------------------------------------------------
 Update on votings v  (cost=0.00..788637465.40 rows=91339856 width=1671)
   ->  Seq Scan on votings v  (cost=0.00..788637465.40 rows=91339856 width=1671)
         SubPlan 1
           ->  Index Scan using idx_voter_rl_person_id on voters pv  (cost=0.56..8.58 rows=1 width=9)
                 Index Cond: (rl_person_id = v.person_id)
(5 registros)

這是我的投票索引

Índices:
    "votings_pkey" PRIMARY KEY, btree (id)
    "votings_election_id_voter_id_key" UNIQUE CONSTRAINT, btree (election_id, person_id)
    "votings_external_id_external_source_key" UNIQUE CONSTRAINT, btree (external_id, external_source)
    "idx_votings_updated_at" btree (updated_at DESC)
    "idx_votings_vote_party" btree (vote_party)
    "idx_votings_vote_state_vote_party" btree (vote_state, vote_party)
    "idx_votings_voter_id" btree (person_id)
Restrições de chave estrangeira:
    "votings_election_id_fkey" FOREIGN KEY (election_id) REFERENCES elections(id)
    "votings_voter_id_fkey" FOREIGN KEY (person_id) REFERENCES people_all(id)

伙計們,誰在更新運行緩慢方面發揮最大作用? 行數或正在使用的連接?

我可以在這里提出的一個建議是對子查詢查找使用覆蓋索引:

CREATE INDEX idx_cover ON voters (person_id, number);

雖然在 select 的上下文中,這可能不會比您當前在person_id上的索引有太大優勢,但在更新的上下文中,它可能更重要。 原因是對於更新,此索引可能會減輕 Postgres 在更新之前必須在其 state 中創建和維護原始表的副本。

如果您在voting中實際有 91339856 行,那么對voters的 91339856 次索引掃描肯定是主要的成本因素。 順序掃描會更快。

如果您不強制 PostgreSQL 進行嵌套循環連接,您可能會提高性能:

UPDATE votings
SET voter_id = voters.number
FROM voters
WHERE votings.person_id = voters.person_id;

更新表中的所有行將非常昂貴。 我建議重新創建表:

create temp_votings as
    select v.*, vv.vote_id
    from votings v join
         voters vv
         on vv.person_id = v.person_id;

對於此查詢,您需要一個關於votes(person_id, vote_id)的索引。 我猜person_id可能已經是主鍵了; 如果是這樣,則不需要額外的索引。

然后,您可以替換現有表——但首先要備份它:

truncate table votings;

insert into votings ( . . . )    -- list columns here
    select . . .                 -- and the same columns here
    from temp_votings;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM