我有两个非常相似的查询:
WITH USAGE AS NOT MATERIALIZED ( SELECT
ocd.*,
1 AS conf_suma
FROM(
SELECT o, o.agreement_id AS agreement_id
FROM "order_bt" o
WHERE o.sys_period @> sys_time()
AND (o.app_period && tstzrange( '2021-01-01', '2021-02-01' ))
)ocd
)
SELECT
*,
(conf_suma/6) ::numeric( 10, 2 ) as group_nds,
(SELECT sum(conf_suma) from USAGE sq WHERE sq.agreement_id = agreement_id) as total_suma -- #1 SLOW
-- #2 FAST: (SELECT sum(conf_suma) from USAGE sq WHERE sq.agreement_id = 3385) as total_suma
FROM USAGE
WHERE agreement_id = 3385 -- LAST WHERE
它们的区别仅在于这部分sq.agreement_id = agreement_id
VSsq.agreement_id = 3385
为什么在第一种情况下不应用优化?在我看来,优化器可以从中LAST WHERE
看出只有一个agreement_id
. 所以agreement_id
就像常数一样。如果我们将此常量折叠到slow
子查询中,它将与子查询相同fast
。这是规划师改进的地方吗?
PS。在我对生产的查询中,这导致查询运行 12 秒而不是 20 毫秒