【问题标题】:Outer apply vs inline query外部应用与内联查询
【发布时间】:2019-04-12 14:11:05
【问题描述】:
应该在这两个查询之间进行选择还是可以使用任何一个?
内联查询
select
*,
(select count(*) from t2 where Id=t1.RefId) as Count
from t1
外用
select
*,
c.Count
from t1
outer apply (select count(*) as Count from t2 where Id=t1.RefId) c
【问题讨论】:
标签:
sql
tsql
sql-server-2008
【解决方案1】:
正如 Gordon 在上面的评论中所说,代码中使用的外部应用应该与非外部应用查询具有相同或相似的执行计划。但是,如果您有多个这样的标量子查询:
select
*,
(select Min(Val) from t2 where Id=t1.RefId) as Minimum
(select Max(Val) from t2 where Id=t1.RefId) as Maximum
(select count(*) from t2 where Id=t1.RefId) as Count
from t1
子查询之间的唯一区别是返回值,那么外部应用查询可能更有效:
select
*,
c.Minimum,
c.Maximum,
c.Count
from t1
outer apply (select Min(Val) as Minimum,
Max(Val) as Maximum,
count(*) as Count,
from t2 where Id=t1.RefId) c