gpt4 book ai didi

postgresql - Postgres 嵌套循环顺序

转载 作者:行者123 更新时间:2023-11-29 13:37:28 29 4
gpt4 key购买 nike

我有以下查询:

SELECT t1.c1 FROM t1,t2 WHERE t1.c2 = 'X' AND t1.id = t2.id AND t2.c3 = 'Y';

Postgres 为这个查询生成两个计划,类似于:

Nested Loop (rows=1 width=7) (actual rows=1 loops=1)
-> Index Scan using idx1 on t1 (rows=1 width=7) (actual rows=4 loops=1)
-> Index Scan using idx2 on t2 (rows=1 width=7) (actual rows=0 loops=7)

或:

Nested Loop (rows=1 width=7) (actual rows=1 loops=1)
-> Index Scan using idx2 on t2 (rows=4 width=7) (actual rows=1000000 loops=1)
-> Index Scan using idx1 on t1 (rows=1 width=7) (actual rows=0 loops=1000000)

因此,有时会为外循环选择 t1,有时会选择 t2。如果选择第二个计划,性能绝对糟糕。

我的问题是,如何强制 Postgres 始终使用第一个查询计划,外循环中有 t1?

最佳答案

确保您定期运行ANALYZE。估计值相差甚远。

顺便说一句,Postgres 可能不在乎,但你可能

得到更好的结果
SELECT T1.c1 FROM t1 JOIN t2 ON t1.id=t2.id
WHERE t1.c2='X' AND t2.c3='Y';

关于postgresql - Postgres 嵌套循环顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5890817/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com