子查询运行速度非常慢SQL Server

时间:2016-04-19 21:18:59

标签: sql sql-server subquery

以下查询在没有ttfj_wtd和ttfj_mtd子查询的情况下运行得非常快。但如果没有重新加入,他们会跑5分多钟。关于如何调整它的任何想法?

select eid, tech_id, tech_name, w_start, w_end, m_start, m_end
,(select firstname+' '+lastname from ems_nyc_employee where eid=a.supeid) as   SupName
,(select firstname+' '+lastname from ems_nyc_employee where eid=a.mngreid) as MngrName
,activitydate
,shift_start+' - '+shift_end as [shift]
,shift_start_time
,login_time
,first_ip_time
,datediff(mi, shift_start_time, first_ip_time) as ttfj_yest
,(select avg(datediff(mi, shift_start_time, first_ip_time)) from arr_tech a2 where a2.eid=a.eid and a2.activitydate between w_start and w_end) as ttfj_wtd
,(select avg(datediff(mi, shift_start_time, first_ip_time)) from arr_tech a2 where a2.eid=a.eid and a2.activitydate between m_start and m_end) as ttfj_mtd  
from 
arr_tech a, dates d
where d.rep_date=convert(date, getdate()-1) and a.activitydate=convert(date, getdate()-1)

1 个答案:

答案 0 :(得分:0)

这是为了便于阅读而修改的代码:

select eid, tech_id, tech_name, w_start, w_end, m_start, m_end,
       (select firstname+' '+lastname
        from ems_nyc_employee e
        where e.eid = a.supeid
       ) as SupName,
       (select firstname+' '+lastname
        from ems_nyc_employee e
        where e.eid = a.mngreid
       ) as MngrName,
       activitydate,
       (shift_start+' - '+shift_end) as [shift],
       shift_start_time,
       login_time,
       first_ip_time,
       datediff(mi, shift_start_time, first_ip_time) as ttfj_yest,
       (select avg(datediff(mi, shift_start_time, first_ip_time))
        from arr_tech a2
        where a2.eid = a.eid and a2.activitydate between w_start and w_end
       ) as ttfj_wtd,
       (select avg(datediff(mi, shift_start_time, first_ip_time))
        from arr_tech a2
        where a2.eid  = a.eid and a2.activitydate between m_start and m_end
       ) as ttfj_mtd  
from arr_tech a join
     dates d
     on a.activitydate = d.rep_date
where a.activitydate = convert(date, getdate() - 1);

首先,您需要外部查询的索引:arr_tech(rep_date)dates(rep_date)

然后,您需要子查询的索引:ems_nyc_employee(eid, firstname, lastname)arr_tech(eid, m_start, m_end)

如果这些索引不起作用,您可能需要重写查询。但是,这可能就足够了。

关于格式化的说明:

  • 从不FROM子句中使用逗号; 始终使用显式JOIN语法。
  • 限定所有列名称,但尤其是相关子查询中的列名称。很容易让相关条件变得错误,并且很容易尝试修复它。
  • 尝试格式化您的查询,就好像您必须再次阅读和理解它一样。