我有一个 users
表,其中包含 points
列。用户 id
不是自增的,而是来自 Twitter 的用户 ID。
我正在尝试通过 username
选择用户(因此总是 1 个用户)并选择它之前的 10 行和之后的 10 行。
此外,它应该按积分排序,我应该得到所选用户的排名。
我正在使用 Laravel 4 和 Eloquent,但我很确定这不能用 Eloquent 完成。
+-----------+--------------+------------+
| id | username | vote_count |
+-----------+--------------+------------+
| 123456789 | user1 | 150 |
| 123456789 | user2 | 101 |
| 123456789 | user3 | 90 |
| 123456789 | user4 | 88 |
| 123456789 | user5 | 70 |
| 123456789 | user6 | 67 |
| 123456789 | user7 | 65 |
| 123456789 | user8 | 55 |
| 123456789 | user9 | 54 |
| 123456789 | user10 | 45 |
| 123456789 | user11 | 44 |
| 123456789 | user12 | 42 |
+-----------+--------------+------------+
假设我想按 vote_count
对这个表进行排序,而不是选择 user5
并按给定顺序选择它之前和之后的 2 个用户。
希望我说清楚了
最佳答案
像这样:
select * from
(
select * from
(
select * from t where vote_count<=
(select vote_count
from t
where username ='user5')
ORDER BY vote_count desc
LIMIT 3
) as T1
UNION
select * from
(
select * from t where vote_count>
(select vote_count
from t
where username ='user5')
ORDER BY vote_count ASC
LIMIT 2
) as T2
) as T3 ORDER BY VOTE_COUNT DESC
关于php - 按指定顺序选择匹配行前后的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19722725/