我试图显示我的排行榜的前15名玩家,但我还想确保只有一个SQL请求显示请求排行榜的玩家
让我们只将棋盘减少到4名玩家。
想象一下,我(要求查看董事会)排在第二位,董事会应该显示以下内容
pos,name
1,bob
2,ME
3,tony
4,andy
但是让我们想象一下,我排在第150位,那么董事会应该是
pos,name
1,bob
2,tony
3,andy
150,ME
我使用以下请求:
SELECT * FROM
(
SELECT name,rating,
(SELECT COUNT(*)
FROM rank AS t2
WHERE t2.rating > t1.rating)
AS position FROM rank AS t1
LIMIT 15
)
UNION
SELECT name,rating,(SELECT COUNT(*)
FROM rank AS t2
WHERE t2.rating > t1.rating)
AS position FROM rank AS t1
WHERE t1.name = 'ben'
ORDER BY rating DESC
如果我在前15名之间排名,那么董事会会正确显示。 但是,如果我超过前15个查询返回16行,而我是最后一行
简而言之,我想在排行榜上展示15名玩家,但其中一名必须是我
编辑:请注意,两名玩家可以处于相同的排名位置
答案 0 :(得分:0)
SELECT * FROM
(
SELECT name,rating,
(SELECT COUNT(*)
FROM rank AS t2
WHERE t2.rating > t1.rating
AND t1.name <> 'ben')
AS position FROM rank AS t1
LIMIT 14
)
UNION
SELECT name,rating,(SELECT COUNT(*)
FROM rank AS t2
WHERE t2.rating > t1.rating)
AS position FROM rank AS t1
WHERE t1.name = 'ben'
ORDER BY rating DESC
此处,不要在第一个查询中返回您自己的用户并将其限制为14.然后在第二个查询中仅返回您自己的用户。