使用OFFSET和CROSS应用

时间:2018-02-22 08:34:55

标签: sql-server performance

我想弄清楚这里出了什么问题。基本上,如果我从下面的代码块中删除“CLEAR = 0”,我的查询将变为50ms读取。它仍在,持续时间为2.1秒。

[警报]表上的索引似乎也没有帮助。我很遗憾为什么现有WHERE中的一个额外的AND子句会破坏查询。

WITH TempResult AS(
     SELECT Table1.*, p.* FROM Table1
     CROSS APPLY(
          SELECT (CASE WHEN (COUNT(*) = SUM(Alerts.ACK+0)) THEN 1 ELSE 0 END) AS ACK,
               MIN(Alerts.Visited+0) AS VisitedAlert FROM Alerts
          INNER JOIN AlertRecipients on Alerts.Id = AlertRecipients.AlertID
               AND AlertRecipients.UserID = @userID 
          WHERE Table1.Id = Alerts.Table1ID AND Alerts.[CLEAR] = 0
     ) p WHERE VisitedAlert IS NOT NULL
), TempCount AS ( 
     SELECT COUNT(*) AS MaxRows FROM TempResult
)
SELECT * FROM TempResult, TempCount 
ORDER BY cast(STUFF(VID, 1, 1, '') as int) Desc OFFSET 0 ROWS FETCH NEXT 14 ROWS ONLY

1 个答案:

答案 0 :(得分:0)

我找到了一个对我看起来写得不好的初始查询的答案。我猜这些东西只是由SQL优化器读取的。

WITH TempResult AS(
SELECT p.* FROM 
(Select Table1.Id, Table1.PeopleID,
    (CASE WHEN (COUNT(*) = SUM(Alerts.ACK+0)) THEN 1 ELSE 0 END) AS AllACKed, MIN(Alerts.Visited+0) AS VisitedAlert FROM Table1
    LEFT JOIN Alerts AS Alerts
          INNER JOIN AlertRecipients AS AlertRecipients on AlertRecipients.AlertID = Alerts.Id AND AlertRecipients.UserID = @userID
    on Alerts.Table1ID = Table1.Id AND Alerts.[CLEAR] = 0
          GROUP BY Table1.Id, Table1.PeopleID
     ) p WHERE (<'any user given filter on p'>)
), TempCount AS ( 
SELECT COUNT(*) AS MaxRows FROM TempResult
)
SELECT * FROM TempResult, TempCount ORDER BY Id Desc OFFSET 0 ROWS FETCH NEXT 15 ROWS ONLY