PostgreSQL使用OFFSET 0阻止子查询内联

时间:2015-09-09 01:09:33

标签: postgresql indexing subquery inlining

我在where子句中有一个子查询,它在每次评估时扫描整个表。

SELECT k, j
FROM tab t1     
WHERE t1.x > (SELECT AVERAGE(x) FROM tab t2 where t1.n = t2.n)
order by k, j 
limit 100;

当我将OFFSET 0添加到子查询的末尾时,查询计划没有变化。

SELECT k, j
FROM tab t1     
WHERE t1.x > (SELECT AVERAGE(x) FROM tab t2 where t1.n = t2.n OFFSET 0) 
order by k, j
limit 100; 

参考此post。优化围栏,“OFFSET 0”,在这种情况下在where子句中不起作用吗?

1 个答案:

答案 0 :(得分:0)

假设平均值是针对n的大多数值计算的,请使用CTE以获得更好的效果:

WITH avg AS (
  SELECT n, average(x) FROM tab GROUP BY n
)
SELECT k, j
FROM tab
JOIN avg USING (n)    
WHERE x > average
ORDER BY k, j
LIMIT 100;