全部,
我有一个包含大约 250000 条记录的用户表。我有以下查询(请注意,我是 SQL 新手),但执行需要很长时间。我检查了执行计划,执行时间的 %60 被 2 种占用。
SELECT TOP 50
Flows_Users.UserName,
Flows_Users.UserID,
Flows_Users.ImageName,
Flows_Users.DisplayName,
Flows_UserBios.bio,
FlowsCount = (
SELECT Count(1)
FROM Flows_Flows
WHERE UserID = Flows_Users.UserID
AND Flows_Flows.Active = '1'
),
BeatsCount = (
SELECT Count(1)
FROM Flows_Beats
WHERE UserName_ID = Flows_Users.UserID
AND Flows_Beats.Active = '1'
),
FollowersCount = (
SELECT Count(1)
FROM Flows_Follow
WHERE FOLLOWING = Flows_Users.UserID
),
FollowingCount = (
SELECT Count(1)
FROM Flows_Follow
WHERE FOLLOWER = Flows_Users.UserID
),
ISNULL(SUM(Flows_Flows_Likes_Dislikes.[Like]), 0) AS Likes,
ISNULL(SUM(Flows_Flows_Likes_Dislikes.Dislike), 0) AS DisLikes
FROM Flows_Users
LEFT JOIN Flows_Flows
ON Flows_Users.UserID = Flows_Flows.UserID
LEFT JOIN Flows_UserBios
ON Flows_Users.UserID = Flows_UserBios.userid
LEFT JOIN Flows_Flows_Likes_Dislikes
ON Flows_Flows.FlowID = Flows_Flows_Likes_Dislikes.FlowID
WHERE Flows_Users.UserID = Flows_Users.UserID
GROUP BY Flows_Users.UserID,
Flows_Users.UserName,
Flows_Users.ImagePath,
Flows_Users.ImageName,
Flows_Users.DisplayName,
Flows_UserBios.bio
ORDER BY
[Likes] DESC,
[Dislikes] ASC,
FlowsCount DESC
我知道这是一团糟,但是当桌子只有数万张时,它就完成了工作。有什么办法可以让这更快吗?现在执行最多需要 5-10 分钟。这也在一个存储过程中,我觉得我有需要索引、索引的列。