添加条件后查询运行缓慢

时间:2012-05-10 20:11:10

标签: sql ms-access ms-access-2010

在其他人的帮助下,我有这个sql语句,用于计算表格中记录之间的里程数(+或 - )。问题是,当我向计算值添加一个标准(> 0)时,它会大大减慢我的查询速度。如果我将标准添加到任何其他字段,那么事情就会按预期运行(没有长时间延迟)。

SELECT T1.Date, 
       T1.Route, 
       T1.BookingID, 
       T1.StreetNumber, 
       T1.Street, 
       T1.Arrive, 
       T1.Perform, 
       T1.Miles, 
       T1.Miles - (SELECT Miles 
                   FROM   Test1 AS T2 
                   WHERE  T2.Route = T1.Route 
                          AND T2.IDNumber = (SELECT Min(IDNumber) 
                                             FROM   Test1 AS T3 
                                             WHERE  T3.Route = T1.Route 
                                                    AND T3.IDNumber > 
                                                        T1.IDNumber)) AS 
       Difference 
FROM   Test1 AS T1 
GROUP  BY T1.Date, 
          T1.Route, 
          T1.BookingID, 
          T1.StreetNumber, 
          T1.Street, 
          T1.Arrive, 
          T1.Perform, 
          T1.Miles, 
          T1.IdNumber, 
          T1.Status, 
          T1.Activityy 
HAVING (( ( [T1].[Miles] - (SELECT Miles 
                            FROM   Test1 AS T2 
                            WHERE  T2.Route = T1.Route 
                                   AND T2.IDNumber = (SELECT Min(IDNumber) 
                                                      FROM   Test1 AS T3 
                                                      WHERE  T3.Route = T1.Route 
                                                             AND T3.IDNumber > 
                                                     T1.IDNumber)) ) > 0 )) 
ORDER  BY T1.IdNumber; 

1 个答案:

答案 0 :(得分:0)

你的区别只是找到了里程的下一条记录。

如果数据库支持row_number()或lag(),则可以使用Windows函数而不是多个自联接来重写此查询。这应该可以解决性能问题。

否则,重写查询以使连接位于“from”子句中。这也应该解决问题。

最后,如果要使用临时表,请将所有结果放在临时表中,然后再进行选择。 (这不是我的首选方法,但对于一次性查询,它可能是最快的解决方案。)