如何优化以下查询

时间:2016-09-11 06:55:03

标签: sql sql-server

我试图优化以下查询。正在使用的两个子查询可以将其转换为单个查询。

select fn.id,
(select top 1 s.rid from find f join status s on f.fid = s.fid 
                    where f.fid = fn.id and f.active = 1) as rid,
(select top 1 f.gid from find f 
                    where f.fid = fn.id and f.active = 1) as gid
           from finding fn where f.tid = 'abcd'

我已经将CWE用于连接子查询,因为它会在每次迭代中反复执行,但我想问一些DBA专家,这可能是以下查询优化的可能和最佳解决方案。任何帮助是极大的赞赏。

2 个答案:

答案 0 :(得分:2)

使用OUTER APPLY

SELECT fn.id, 
       oa.rid, 
       oa.gid 
FROM   finding fn 
       OUTER apply (SELECT TOP 1 s.rid, 
                                 f.gid 
                    FROM   find f 
                           JOIN status s 
                             ON f.fid = s.fid 
                    WHERE  f.fid = fn.id 
                           AND f.active = 1) oa 
WHERE  f.tid = 'abcd' 

注意:您正在使用TOP 1而不是Order by,您将获得结果中的任意记录。

答案 1 :(得分:0)

这应该表现得更好:

select fn.id, t.rid, t.gid
from finding fn 
join (
   select f.fid, s.rid, f.gid,
          row_number() over (order by select null) as rn 
   from find f 
   join status s on f.fid = s.fid 
   where f.active = 1
) as t on t.fid = fn.id and rn = 1
where fn.tid = 'abcd'

原始查询中的TOP 1在没有ORDER BY子句的情况下执行,因此不清楚应该选择哪条记录。您可以使用确定顶行选择的字段替换上述查询中的select null