【问题标题】:Update multiple rows with 'CASE WHEN EXISTS' too slow使用“CASE WHEN EXISTS”更新多行太慢
【发布时间】:2020-12-23 04:17:26
【问题描述】:

我有这个问题

update t_reconcile_biller b set status = case when exists (
    SELECT i.credit_amount, i.recipt_no,  
    i.credit_acct_no, i.recon_date 
    FROM t_reconcile_t24 i 
    WHERE i.debit_acct_no = 'IDR1720600010001'
    and b.col_4 = i.credit_amount
    AND b.col_7 = i.recipt_no 
    AND b.col_2 = i.card_no 
    AND i.status <> 5 
) then 1 else 2 end
where b.status <> 5 AND b.file_name in ('20200923-bnf', '20200922-bnf')
AND b.col_13 = 'DESTIONATION' AND b.col_4 <> '0'
AND b.col_14 in ('A', 'FC')

使用 postgres 运行需要 52 秒,其中 t_reconcile_biller 有 3.900 行,而 t_reconcile_t24 有 32.000 行。

我怎样才能使这个查询更快更高效?

【问题讨论】:

  • 请用您正在使用的数据库标记您的问题

标签: sql postgresql performance


【解决方案1】:

exists 子句中出现的表上的以下索引可能会有所帮助:

CREATE INDEX rec_idx ON t_reconcile_t24 (
    credit_amount, recipt_no, card_no, status );

如果使用,Postgres 可以使用上述索引快速查找目标表中的每条记录。此外,外部表上的以下索引也可能会有所帮助:

CREATE INDEX biller_idx ON t_reconcile_biller (
    status, file_name, col_4, col_13, col_14 );

【讨论】:

  • 顺便问一下,更新查询(在 topicstarter 的帖子中)是否优化为左连接?如果没有,那么这意味着每一行都针对整个“t24”表进行检查,不是吗(尽管如果它们没有相关的索引则很难将其视为优化,所以基本上它们仍然会做同样的事情)
猜你喜欢
  • 2019-02-02
  • 1970-01-01
  • 2022-01-10
  • 1970-01-01
  • 2017-04-11
  • 1970-01-01
  • 1970-01-01
  • 2012-05-07
  • 1970-01-01
相关资源
最近更新 更多