在 Oracle 中使用 WITH 子句优化多个子查询
Optimize multiple subselects with WITH clause in Oracle
我有一个查询:
select
qsn.code,
(select prs.display_name from prs where prs.id = qsn.fk_prs) display_name,
(select prs.address from prs where prs.id = qsn.fk_prs) address,
(select prs.tel from prs where prs.id = qsn.fk_prs) tel
from
qsn
where
qsn.register_date between :x1 and :x2
当我查看查询的执行计划时,它查询prs
table 3次(每次使用INDEX UNIQUE SCAN
) .
不知是否可以使用WITH子句查询一次prs
table?我怎样才能这样写查询。
我要提一下,因为每个 table 都有数百万条记录,加入它们会使查询变得很慢。
使用连接:
select qsn.code, prs.display_name, prs.address, prs.tel
from qsn
left join prs on prs.id = qsn.fk_prs
where qsn.register_date between :x1 and :x2
使用 with 子句你的查询是这样的:
with abc as (select id,
display_name ,
address ,
tel
from prs)
select
qsn.code,
abc.display_name,
abc.address,
abc.tel
from qsn
inner join abc
on qsn.fk_prs = abc.id
where qsn.register_date between :x1 and :x2 ;
ps: 未测试。
我有一个查询:
select
qsn.code,
(select prs.display_name from prs where prs.id = qsn.fk_prs) display_name,
(select prs.address from prs where prs.id = qsn.fk_prs) address,
(select prs.tel from prs where prs.id = qsn.fk_prs) tel
from
qsn
where
qsn.register_date between :x1 and :x2
当我查看查询的执行计划时,它查询prs
table 3次(每次使用INDEX UNIQUE SCAN
) .
不知是否可以使用WITH子句查询一次prs
table?我怎样才能这样写查询。
我要提一下,因为每个 table 都有数百万条记录,加入它们会使查询变得很慢。
使用连接:
select qsn.code, prs.display_name, prs.address, prs.tel
from qsn
left join prs on prs.id = qsn.fk_prs
where qsn.register_date between :x1 and :x2
使用 with 子句你的查询是这样的:
with abc as (select id,
display_name ,
address ,
tel
from prs)
select
qsn.code,
abc.display_name,
abc.address,
abc.tel
from qsn
inner join abc
on qsn.fk_prs = abc.id
where qsn.register_date between :x1 and :x2 ;
ps: 未测试。