我有以下查询:
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?
答案 0 :(得分:1)
确保您定期运行ANALYZE
。估计结束了。
SELECT T1.c1 FROM t1 JOIN t2 ON t1.id=t2.id
WHERE t1.c2='X' AND t2.c3='Y';
答案 1 :(得分:0)
试图使用左连接?这应该强制连接顺序并返回相同的结果,因为t2.c3上的子句:
SELECT t1.c1
FROM t1 LEFT JOIN t2 ON t1.id = t2.id
WHERE t1.c2 = 'X' AND t2.c3 = 'Y';