我有点困惑,为什么使用 with 子句的简单 SQL 查询比将它们放在子查询中花费的时间要长得多。我的 IDE 上的一个超过 1000 万条记录的实例使用 with 子句运行 30 分钟以上,而使用子查询仅运行 <10 秒。
下面只列出一个简单的例子:
with table1 as (select tb1.a, tb1.b, tb2.c, tb3.d
from tablea
where a > 0 and b = 2016)
table2 as (select a, b, c, d, e, f
from table1 tb1
left join table2 tb2 on tb1.a=tb2.a
left join table3 tb3 on tb1.b=tb2.b)
select * from table2
与将它们作为子查询相比:
select * from (select a, b, c, d, e, f
from (select tb1.a, tb1.b, tb2.c, tb3.d
from tablea
where a > 0 and b = 2016) tb1
left join table2 tb2 on tb1.a=tb2.a
left join table3 tb3 on tb1.b=tb2.b) table2
后者查询的完成速度比前者快得多。但是,从查询结构的角度来看,前者要容易得多,因此如果可能的话,我更愿意这样做。
不知道这个巨大的差异是由于我在解释时使用的IDE(DBeaver),还是基于SQL语句逻辑本身?
谢谢你。
这是因为在 Postgres CTE 中充当优化障碍。一种解决方法(具有几乎相同的句法结构)是用TEMP VIEW
s替换 CTE :
CREATE TEMP VIEW v1 AS
SELECT ta.a, ta.b, ta.c, ta.d
FROM tablea ta
WHERE a > 0 and b = 2016
;
CREATE TEMP VIEW v2 AS
SELECT a, b, c, d, e, f
FROM v1
LEFT JOIN table2 tb2 ON v1.a=tb2.a
LEFT JOIN table3 tb3 ON v1.b=tb3.b
;
SELECT * from v2;
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句