SQL Cross应用语句表现不佳

时间:2017-06-20 22:50:18

标签: sql sql-server-2008 optimization

以下语句执行速度意外缓慢,子表确实包含很多行,但父表没有,索引看起来很好 - 我认为有更好的方法可以做到这一点。

SELECT P.[ID] 
,C1.[MinChildDate]
,C2.[MaxChildDate]
FROM Parent AS P
CROSS APPLY
(
SELECT 
MIN([Date]) AS MinChildDate
FROM Child 
WHERE Child.ParentID=P.ID
) AS C1
CROSS APPLY
(
SELECT 
MAX([Date]) AS MAXChildDate
FROM Child 
WHERE Child.ParentID=P.ID
) AS C2

2 个答案:

答案 0 :(得分:1)

删除CROSS APPLY以将Child表的逻辑读取减半。

SELECT P.[ID] 
,C1.[MinChildDate]
,C1.[MaxChildDate]
FROM Parent AS P
CROSS APPLY
(
SELECT 
MIN([Date]) AS MinChildDate,
MAX([Date]) AS MAXChildDate
FROM Child 
WHERE Child.ParentID=P.ID
) AS C1

答案 1 :(得分:1)

只需通过查询使用一个简单的组:

SELECT
      P.[ID]
    , MIN(child.[Date]) AS MinChildDate
    , MAX(child.[Date]) AS MAXChildDate
FROM Parent AS P
      INNER JOIN Child ON P.ID = Child.ParentID
GROUP BY
      P.[ID]
;