我有以下MySQL查询:
SELECT serverusers.serverID, serverusers.userID, serverusers.xpTotal, users.bot
FROM users INNER JOIN serverusers ON users.userID = serverusers.userID
WHERE users.bot = 'false' && serverID = 318467989655781389
ORDER BY xpTotal DESC
我需要用它来找到它的排名"特定的userID
是。例如:
+---------+-----------+------------+----------+
serverID | userID | xpTotal | bot |
----------------------------------------------+
50 | 23892 | 200 | false |
----------------------------------------------+
50 | 27173 | 180 | false |
----------------------------------------------+
50 | 17294 | 150 | false |
----------------------------------------------+
50 | 72973 | 110 | false |
如果我要提供userID
17294
,则应返回3
,因为17294
是第3行。
答案 0 :(得分:0)
也许一种简单的方法是使用变量:
SELECT suu.*
FROM (SELECT su.serverID, su.userID, su.xpTotal, u.bot,
(@rn := @rn + 1) as rn
FROM users u INNER JOIN
serverusers su
ON u.userID = su.userID CROSS JOIN
(SELECT @rn := 0) params
WHERE u.bot = 'false' AND su.serverID = 318467989655781389
ORDER BY xpTotal DESC
) suu
WHERE userID = ?;
最新版本的MySQL在SELECT
之前处理ORDER BY
中的变量。因此,您可能需要一个额外的子查询层:
SELECT suu.*
FROM (SELECT su.serverID, su.userID, su.xpTotal, u.bot,
(@rn := @rn + 1) as rn
FROM (SELECT su.serverID, su.userID, su.xpTotal, u.bot
FROM users u INNER JOIN
serverusers su
ON u.userID = su.userID
WHERE u.bot = 'false' AND su.serverID = 318467989655781389
ORDER BY xpTotal DESC
) suu CROSS JOIN
(SELECT @rn := 0) params
) suu
WHERE userID = ?;