好的,所以我有一个'用户'表,其中包含'id'列和'score'列。 'id'是主键,'score'可以是任何正整数,并且用户可以具有相同的分数。
我需要选择3行:
有关如何在SQL中执行此操作的任何建议吗?谢谢!
更新
很抱歉,我现在意识到我需要做更多关于如何处理具有相同分数的多行的选择。我已经决定将排除分数排除在外,因此我正在寻找目标用户获得次高分和次低分的用户。
示例数据:
id score
1 0
2 5
3 9
4 5
5 5 *
6 5
7 8 *
8 3 *
所以,如果我的目标用户的id = 5,我想要带有ID为7,5和8的行
答案 0 :(得分:2)
首先,查询该特定用户的分数:
select score
from users
where id = 42
假设用户42的分数是6.然后您可以查询下一个用户:
select name
, score
from users
where score > 6
order by
score
limit 1
和之前的用户一样:
select name
, score
from users
where score < 6
order by
score desc
limit 1
答案 1 :(得分:1)
set @ID = 3;
set @Score = (select score
from users
where ID = @ID);
select ID, Score
from (select U.ID, U.Score
from users as U
where U.ID <> @ID and
U.Score < @Score
order by U.Score desc limit 1) as P
union all
select U.ID, U.Score
from users U
where U.ID = @ID
union all
select *
from (select U.ID, U.Score
from users as U
where U.ID <> @ID and
U.Score > @Score
order by U.Score limit 1) as A
order by Score;
答案 2 :(得分:0)
我认为一个问题可能是你可能有三个以上相同分数的用户,你不知道谁是“直接在目标上方”或“直接在其下方”。
您可以考虑子查询。内部查询类似于
select score from users where last='Who' and first='Doctor'
对于外部查询,这将使您直接进入上面的那个:
select * from users
where score >= (select score from users where last='Who' and first='Doctor')
order by score asc
limit 1
我会将用户直接留在下面作为练习OP。
答案 3 :(得分:0)
select name, score
from users
where id >= select id
from users
where id < 42
order score
limit 1
order by score
limit 3
答案 4 :(得分:0)
因为我需要格式化以讨论Andomar的提议:
鉴于一些用户得分相同(6):
mysql> select * from sam1vp;
+------+-------+
| user | score |
+------+-------+
| 40 | 5 |
| 41 | 6 |
| 42 | 6 |
| 43 | 6 |
| 44 | 7 |
+------+-------+
>
/ <
的查询不会返回最近的邻居:
mysql> select user,score from sam1vp where score > 6 order by score limit 1;
+------+-------+
| user | score |
+------+-------+
| 44 | 7 |
+------+-------+
使用>=
/ <=
并排除目标用户:
mysql> select user,score from sam1vp where score >= 6 and user != 42 order by score limit 1;
+------+-------+
| user | score |
+------+-------+
| 41 | 6 |
+------+-------+