有个SQL:
select top 20 a.ServiceNo, a.Name,b.Seq_Points,c.Points from
TR_Driver a left join T21_DriverOptInfoDaily_Points b
on a.ServiceNo=b.ServiceNo and b.CompanyID=a.CompanyID
left join TR_DriverPointInfo c
on a.ServiceNo=c.ServiceNo and c.CompanyID=b.CompanyID
where a.IsDelete=0 and DATEDIFF(SECOND,'2014/2/25 10:00:00',b.Data_Dt)=0
and DATEDIFF(SECOND,'2014/2/25 10:00:00',c.Data_Dt)=0
and b.CompanyID=(select CompanyID from TR_Driver where ServiceNo=843391 and IsDelete=0) order by Seq_Points
T21_DriverOptInfoDaily_Points这个表有两百多万条数据
查询的性能非常差,结果要20多秒才能出来,大家看看有什么好的办法优化下??
------解决方案--------------------
T21_DriverOptInfoDaily_Points的Data_Dt上创建聚集索引(没有的话)
TR_Driver的ServiceNo上创建索引(没有的话)
TR_Driver的CompanyID上创建索引(没有的话)
TR_DriverPointInfo的TR_DriverPointInfo创建索引(没有的话)
改写sql
select top 20 a.ServiceNo, a.Name, b.Seq_Points, c.Points
from TR_Driver a
left join T21_DriverOptInfoDaily_Points b on a.ServiceNo = b.ServiceNo
and b.CompanyID = a.CompanyID
left join TR_DriverPointInfo c on a.ServiceNo = c.ServiceNo
and c.CompanyID = b.CompanyID
where a.IsDelete = 0
and b.Data_Dt= '2014/2/25 10:00:00'
and c.Data_Dt= '2014/2/25 10:00:00'
and b.CompanyID = a.CompanyID
and a.ServiceNo = 843391
order by Seq_Points
------解决方案--------------------
select?top?20?a.ServiceNo,?a.Name,b.Seq_Points,c.Points?
from?TR_Driver?a??
left?join??
(select u.Seq_Points,u.ServiceNo,u.CompanyID from T21_DriverOptInfoDaily_Points u
inner join
(select?CompanyID?from?TR_Driver?where?ServiceNo=843391?and?IsDelete=0) v on u.CompanyID=v.CompanyID
?)b? on?a.ServiceNo=b.ServiceNo?and?b.CompanyID=a.CompanyID?
left?join?TR_DriverPointInfo?c? on?a.ServiceNo=c.ServiceNo?and?c.CompanyID=b.CompanyID?
where?a.IsDelete=0?and?DATEDIFF(SECOND,'2014/2/25?10:00:00',b.Data_Dt)=0?and?DATEDIFF(SECOND,'2014/2/25?10:00:00',c.Data_Dt)=0??
order?by?Seq_Points
left?join?TR_DriverPointInfo?c? on?a.ServiceNo=c.ServiceNo?and?c.CompanyID=b.CompanyID 这段中 是
c.CompanyID=b.CompanyID 还是 c.CompanyID=a.CompanyID ?根据你需求而定!
------解决方案--------------------
这个脚本的写法和你数据库中设计的关联字段有关系,1:m或是m:n
------解决方案--------------------
把鼠标移到开销74、62那两个上面,看看它用到哪些列,分别建“一个索引”,包住这些列