我有一张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个用户。
希望我能清楚这个
答案 0 :(得分:1)
这样的事情:
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
答案 1 :(得分:0)
您可以使用union
(SELECT id, vote_count
FROM `table`
WHERE id > 123456789
LIMIT 10)
UNION
(SELECT id, vote_count
FROM `table`
WHERE id <= 123456789
LIMIT 10)
ORDER BY vote_count
答案 2 :(得分:-1)
您可以查看SQL FIDDLE
select * from ( (select A.vote_count,A.username from t A join t B on A.vote_count<B.vote_count where B.username='user5' order by A.vote_count DESC limit 2)
UNION
(select A.vote_count,A.username from t A join t B on A.vote_count>=B.vote_count where B.username='user5' order by A.vote_count limit 3)) as T order by vote_count desc