优化sql Query,执行时间过长

时间:2017-12-05 10:35:34

标签: sql sql-server query-optimization

以下sql查询需要很多才能返回结果

vcd

我怎样才能做得更好?

4 个答案:

答案 0 :(得分:1)

我会考虑将IN's更改为JOIN's

select count(*) 
from list_declarations d join service s on d.id_antenne = s.id
                         join affectation_service_dr sdr on sdr.id_dr = s.id_direction
where sdr.id_service = 15

然后我再次检查性能,看看where子句和外键中使用的列是否有任何索引。

答案 1 :(得分:1)

试试这个:

SELECT count(*)
FROM 
  List_declarations d
  INNER JOIN Service 
  ON d.Id_antenne = s.id

  INNER JOIN affectation_service_dr a
  s.id_direction = a.id_dr

WHERE 
  a.id_service = 15
  • 它可能有所不同,它可能没有(但通常是编写这种性质的查询的更好方法)

无可估量的重要性,是确保将以下内容编入索引:

affectation_service_dr.id_service 
Service.id_direction 
List_declarations.Id_antenne  

如果仍然存在无法通过大量行轻松解释的性能问题(例如,它需要38秒,但它返回的计数为20348957389956845),那么我建议您修改您的问题以包含计划说明({{3 }})

答案 2 :(得分:0)

如果此处不关注“读取未提交的数据”。如果有问题,您仍然可以尝试删除with (nolock)

SELECT count(*)
FROM List_declarations LD WITH (NOLOCK)
WHERE  exists (
   SELECT id
   FROM [Service] S WITH (NOLOCK)
   inner join affectation_service_dr dr WITH (NOLOCK)
   on s.id_direction=dr.id_dr
    WHERE ld.Id_antenne=s.id and dr.id_service = 15
   )

答案 3 :(得分:0)

我尝试了每个人的命题,但似乎没有什么是解决方案,请求所消耗的时间仍然是37s

考虑到请求,我意识到in子句中的查询是针对包含大量数据的表list_declarations中的每一行执行的。以下sql代码工作镍(1s):

declare  @table table( idantenne nvarchar(20))
insert into @table select ID from Service where id_direction in (select id_dr from affectation_service_dr where id_service = 15)
Declare @string AS Nvarchar(MAX) -- It must not be MAX if you have few numbers 
SELECT  @string = COALESCE(@string + ',', '') + idantenne
FROM   @table where idantenne IS NOT NULL
declare @req nvarchar(max)
set @req = 'SELECT * FROM List_declarations Where 1=1  and Id_antenne in (' + @string +' )'
exec (@req)