我在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子句中不起作用吗?
答案 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;