[英]Leaderboard : return 5 records, then the one I want, then 4 more records
I'm constructing a leaderboard, and I want a specific user to be in the middle of the returned records. 我正在构建排行榜,并且我希望特定用户位于返回记录的中间。
In other words, I want 5 higher scored users, then the user I want in the middle, then the next 4 lower: 换句话说,我希望获得5个得分较高的用户,然后是我想要在中间的用户,然后是接下来的4个得分较低的用户:
**users:**
User, Score
Rita, 9
Sue, 8
Bob, 7
Bill, 6
Sam, 5
**ME, 4** <-- This would be the user I want in the middle.
Sally, 3
Simon, 2
John, 1
Jim, 0
I could do it in PHP, but just wanted to try and do it with a more elegant SQL statement. 我可以用PHP做到这一点,但只想尝试使用更优雅的SQL语句来实现。
I have literally no idea how I would even approach it! 我真的不知道该如何处理!
Thanks 谢谢
Something to think about: 需要考虑的事情:
SELECT id,name FROM my_table;
+----+---------+
| id | name |
+----+---------+
| 1 | Adam |
| 2 | Ben |
| 3 | Charlie |
| 4 | Adam |
| 5 | Ben |
| 6 | Dan |
+----+---------+
SELECT * FROM
(SELECT id,name FROM my_table ORDER BY id LIMIT 2) x
UNION
(SELECT id,name FROM my_table ORDER BY id DESC LIMIT 2);
+----+------+
| id | name |
+----+------+
| 1 | Adam |
| 2 | Ben |
| 6 | Dan |
| 5 | Ben |
+----+------+
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.