确保从MySQL查询返回正确的行数

时间:2014-04-30 14:02:20

标签: mysql sql union leaderboard sql-limit

我有一个(游戏)排行榜表,其中包含一个由另一个查询更新的排名。它以ID为中心 - 当我查询表格时,我理想地想要获取N条记录。所以我在记录上做了一个UNION,其限制为N / 2,如下所示:

(SELECT * FROM test1 t WHERE t.rank > (SELECT rank FROM test1 t2 WHERE id=ID)+0 ORDER BY rank LIMIT 0, N/2)
UNION ALL
(SELECT * FROM test1 t WHERE t.rank <= (SELECT rank FROM test1 t2 WHERE id=ID)+0 ORDER BY rank desc LIMIT 0, N/2) ORDER BY rank

虽然在排行榜的顶部时这不起作用,但它只会返回较低的N / 2。有没有办法确保它总能返回N条记录?我确实认为你可以故意获得比所需更多的记录,然后修剪你不需要的记录。虽然我不知道怎么用查询来做这个!

任何帮助表示赞赏:)

2 个答案:

答案 0 :(得分:3)

您可以巧妙地使用order bylimit

来执行此操作
SELECT t.*
FROM test1 t cross join
     (SELECT rank FROM test1 t2 WHERE id = @ID) as theone
ORDER BY ABS(theone.rank - t.rank)
LIMIT N;

然后你可能希望这些按顺序排列:

SELECT t.*
FROM (SELECT t.*
      FROM test1 t cross join
           (SELECT rank FROM test1 t2 WHERE id = @ID) as theone
      ORDER BY ABS(theone.rank - t.rank)
      LIMIT N
     ) t
ORDER BY t.rank;

答案 1 :(得分:0)

尝试以下方法:

(SELECT * FROM test1 t WHERE t.rank > (SELECT rank FROM test1 t2 WHERE id=ID)+0 ORDER BY rank LIMIT 0,N)
UNION ALL
(SELECT * FROM test1 t WHERE t.rank <= (SELECT rank FROM test1 t2 WHERE id=ID)+0 ORDER BY rank desc LIMIT 0,N)
ORDER BY rank
LIMIT 0,N

有关详情,请参阅manual