我对 SQL 中的“子查询”有疑问。假设我想编写一个将使用子查询的查询。我应该使用哪种方法以获得最佳性能?
1)
SELECT a.name, a.surname
FROM (
SELECT tab1.ID, tab1.name, tab2.surname
FROM tab1
INNER JOIN tab2 on tab1.ID = tab2.ID
) a
WHERE a.name = 'John'
with cte1 as (
SELECT tab1.ID, tab1.name, tab2.surname
FROM tab1
INNER JOIN tab2 on tab1.ID = tab2.ID
)
select cte1.name, cte1.surname
from cte1
where cte1.name = 'John'
if object_id('tempdb.dbo.#cte1', 'U') is not null
drop table #cte1;
select tab1.ID, tab1.name, tab2.surname
into #cte1
from tab1
inner join tab2 on tab1.ID = tab2.ID
select #cte1.name, #cte1.surname
from #cte1
where #cte1 = 'John'
通常我使用 1) 方法,以防子查询太复杂,我使用 2)。 在代码清晰度和简单性方面,我认为 2) 是最好的。
我想 3) 中的
#temptable
不使用我的本地 RAM,而是在服务器上创建表,因此它对大表有最好的性能,或者如果我会写类似的东西
if object_id('tempdb.dbo.#cte1', 'U') is not null
drop table #cte1;
select tab1.ID, tab1.name, tab2.surname
into #cte1
from tab1
inner join tab2 on tab1.ID = tab2.ID
;
select #cte1.name, #cte1.surname
from #cte1
where #cte1 = 'John'
;
select #cte1.name, #cte1.surname
from #cte1
where #cte1 = 'Max'
;
在一个窗口中有两个单独的查询。