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