Oracle SQL WITH 语句是否比 subselect 更好
Is Oracle SQL WITH statement better than subselect
我有一个超过 1000 行的 Oracle 查询。使用存储过程将其分解 and/or 在这里不是一个选项。我要把它做得更长。其中哪一个性能更好?我发现 WITH 版本更易于阅读。
/* subselect */
select col01
,col02
from (
select case col01 when 'X' then 1 else 2 end col01
,case col02 when 'Y' then 3 else 4 end col02
from (
select upper(col01) col01
,upper(col02) col02
from (
select 'x' as col01
,'y' as col02
from dual
)
)
)
;
---------------------------------------
/* with statement */
with qry01 as (
select 'x' as col01
,'y' as col02
from dual
)
,qry02 as (
select upper(col01) col01
,upper(col02) col02
from qry01
)
,qry03 as (
select case col01 when 'X' then 1 else 2 end col01
,case col02 when 'Y' then 3 else 4 end col02
from qry02
)
select col01
,col02
from qry03
;
我还发现 CTE WITH
表达式更易于阅读。除此之外还有喜欢它的理由。
- 您可以在主查询中多次使用 CTE 子查询。
- Oracle 优化器可以将 CTE 子查询的结果存储在临时 table 中,该临时 table 创建为 on-the-fly。 (注意,您甚至可以通过未记录的提示强制执行
/*+ MATERIALIZE */
)
- 您可以递归使用 CTE,请参阅 Recursive Subquery Factoring
我有一个超过 1000 行的 Oracle 查询。使用存储过程将其分解 and/or 在这里不是一个选项。我要把它做得更长。其中哪一个性能更好?我发现 WITH 版本更易于阅读。
/* subselect */
select col01
,col02
from (
select case col01 when 'X' then 1 else 2 end col01
,case col02 when 'Y' then 3 else 4 end col02
from (
select upper(col01) col01
,upper(col02) col02
from (
select 'x' as col01
,'y' as col02
from dual
)
)
)
;
---------------------------------------
/* with statement */
with qry01 as (
select 'x' as col01
,'y' as col02
from dual
)
,qry02 as (
select upper(col01) col01
,upper(col02) col02
from qry01
)
,qry03 as (
select case col01 when 'X' then 1 else 2 end col01
,case col02 when 'Y' then 3 else 4 end col02
from qry02
)
select col01
,col02
from qry03
;
我还发现 CTE WITH
表达式更易于阅读。除此之外还有喜欢它的理由。
- 您可以在主查询中多次使用 CTE 子查询。
- Oracle 优化器可以将 CTE 子查询的结果存储在临时 table 中,该临时 table 创建为 on-the-fly。 (注意,您甚至可以通过未记录的提示强制执行
/*+ MATERIALIZE */
) - 您可以递归使用 CTE,请参阅 Recursive Subquery Factoring