我有点困惑为什么使用 with 子句的简单 SQL 查询比将它们放在子查询中花费的时间要长得多。我的 IDE 上超过 100 万条记录的实例使用 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语句逻辑本身?
谢谢你。