这个查询很好,只有一个问题,那就是他的执行时间很长。有人可以向我展示一些很好的优化并解释它们。
SELECT TOP 5 PC.PersonID, P.FirstName, P.LastName, P.A, COUNT(*) Together
FROM PersonCheckIn PC
INNER JOIN Person P ON P.PersonID = PC.PersonID
WHERE CAST(CheckInDate AS DATE) IN (SELECT CAST(CheckInDate AS DATE)
FROM PersonCheckIn C
WHERE C.PersonId = 20) AND
PC.TimeTableID IN (SELECT CIn.TimeTableID
FROM PersonCheckIn CIn
WHERE CIn.PersonId = 20)
AND PC.PersonId <> 20 -- not count same person
GROUP BY PC.PersonId, P.FirstName, P.LastName, P.A
ORDER BY Together DESC;
答案 0 :(得分:0)
避免子查询和IN()语句将大大减少执行时间......
即便如此,CheckInDate
在查询中也不以其表别名作为前缀(而且我们必须猜测女巫表是关注的:(),也许这样做可以做到这一点:
SELECT TOP 5 PC.PersonID, P.FirstName, P.LastName, P.A, COUNT(*) Together
FROM PersonCheckIn PC
INNER JOIN Person P ON P.PersonID = PC.PersonID
INNER JOIN PersonCheckIn LU ON (LU.PersonId = 20 AND PC.CheckInDate = LU.CheckInDate AND PC.TimeTableID = LU.TimeTableID)
WHERE PC.PersonId <> 20 -- not count same person
GROUP BY PC.PersonId, P.FirstName, P.LastName, P.A
ORDER BY Together DESC;
如果没有,请:
- 设置缺少的别名。
- 给出使用数据结构
- 给我们数据例子
- 给我们预期的结果例子。