2

我在获得一个快速的 sql 查询时遇到了一些麻烦。我已经设法得到一个查询来返回我想要的结果,但即使使用正确的索引也需要大约 2 sek 才能运行。

我有这些表:

[Login]
loginID
loginTime
userID

[user]
userID 
userName

[companyParticipant]
userID
companyID

[company]
companyID
organisationID
CompanyName

我想展示的是所有登录时间排名前 10 位的最新登录人。用户所在的公司是我的参与者或组织内的公司,而我是该组织的公司的成员

获取我的组织:

SELECT organisationID 
FROM companys 
WHERE companyID IN (
    SELECT companyID 
    FROM companyParticipant 
    WHERE userID = @userID) 
GROUP BY organisationID 

所以我想要这样的查询:

SELECT TOP 10 userName, LoginTime 
FROM ....
ORDER BY loginID
4

2 回答 2

0
    SELECT userName, loginTime
      FROM
(
    SELECT u.userName, l.loginTime,
           rn = row_number() over (partition BY u.userName
                              ORDER BY l.loginTime DESC)
      FROM companyParticipant cp
      JOIN companys c ON c.companyID = cp.companyID
      JOIN companys c2 ON c2.organisationID = c.organisationID -- same organisation
      JOIN companyParticipant cp2 ON cp2.companyID = c2.companyID -- participants of same org
      JOIN login l ON l.userID = cp2.userID
      JOIN [user] u ON u.userID = l.userID
     WHERE cp.userID = @userID
)          X
     WHERE rn = 1
  ORDER BY loginTime DESC
于 2012-10-12T16:19:39.290 回答
0

这个查询不到一秒钟,速度非常快。看起来很奇怪,因为总是有人登录,并且新登录必须相隔 10 分钟,否则它只会更新最后一次登录,因此不需要打破平局似乎很奇怪。

SELECT      TOP (10) l.loginID, l.loginTime,u.userName
FROM          logins AS l WITH(NOLOCK) INNER JOIN
                        users AS u WITH(NOLOCK) ON l.UserID = u.UserID
WHERE      (l.UserID <> @userID)
AND u.userID IN(SELECT u.userID FROM companyParticipants AS sp2 WHERE sp2.companyID IN (SELECT sc2.companyID FROM company AS sc2 WHERE sc2.organisationID IN(
SELECT sc.organisationID FROM company AS sc LEFT JOIN companyParticipants AS sp ON sc.companyID = sp.companyID WHERE sp.userID = @userID AND sc.organisationID > 0 GROUP BY sc.organisationID
)))
ORDER BY l.loginID DESC
于 2012-10-14T19:21:41.493 回答