2

我有一个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 个用户。

希望我对这个很清楚

4

3 回答 3

1

像这样的东西:

SQLFiddle 演示

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
于 2013-11-01T08:05:10.863 回答
0

你可以使用联合

 (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  
于 2013-11-01T07:59:04.880 回答
-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

于 2013-11-01T08:17:03.540 回答