此查询将为每个用户选择最低排名和下一个排名:
select s.userid, s.min_rank, min(users.rank) as next_rank
from (
select userid, min(rank) as min_rank
from users
group by userid) s left join users
on users.userid = s.userid and s.min_rank<users.rank
group by s.userid
ant 这将显示名称:
select t.userid, t1.name, t2.name
from (
select s.userid, s.min_rank, min(users.rank) as next_rank
from (
select userid, min(rank) as min_rank
from users
group by userid) s left join users
on users.userid = s.userid and s.min_rank<users.rank
group by s.userid ) t
left join users t1 on t.userid=t1.userid and t.min_rank=t1.rank
left join users t2 on t.userid=t2.userid and t.next_rank=t2.rank
结果是:
1 raj frank
2 liz neeta
如果可能有多个用户具有相同的排名,这取决于您要如何处理这种情况,您可以添加以下内容:
group by t.userid
只显示其中之一。也许你也可以GROUP_CONCAT(t1.name), GROUP_CONACT(t2.name)
在选择上使用。