Mysql 在SQL中返回5个结果

Mysql 在SQL中返回5个结果,mysql,sql,limit,Mysql,Sql,Limit,这对我来说有点难解释。但我会一步一步地告诉你我的目标是什么。下面我有一张类似的桌子。我的目标是通过只指定名称来返回5个结果,每5行返回5个结果,并且我希望结果按原样排列 id | names 1 Michael 2. Albert 3. William 4. Abraham 5. Leonardo 6. Elvis 7. Mozart 8. Martin 9. Benjamin 10. Georg

这对我来说有点难解释。但我会一步一步地告诉你我的目标是什么。下面我有一张类似的桌子。我的目标是通过只指定名称来返回5个结果,每5行返回5个结果,并且我希望结果按原样排列

id  | names
1     Michael 
2.    Albert
3.    William       
4.    Abraham  
5.    Leonardo  
6.    Elvis  
7.    Mozart 
8.    Martin  
9.    Benjamin  
10.   George 
11.   Napoleon
12.   John
13.   Christopher 
14.   Michelangelo
15.   Thomas 
16.   Gandhi
17.   Cleopatra
18.   Neil 
19.   Marilyn 
20.   Bill 
假设我想返回5个结果,其中莫扎特的名字在行中可见

下面是我想要的结果:莫扎特的名字在接下来的5行之后就可见了

    6.    Elvis  
    7.    Mozart 
    8.    Martin  
    9.    Benjamin  
    10.   George 
或者让我们假设我想返回5个结果,其中米开朗基罗的名字成行可见

下面是我想要的结果:米开朗基罗的名字就在接下来的两行之后

或者,假设我想返回5个结果,其中Christopher的名字在行中可见

这是我想要的结果,与第二个示例相同:Christopher的名字在接下来的两行后面可见


您可以通过对id进行一些运算来实现这一点:

编辑:

如果ID不正常,则问题更具挑战性。我会用变量来做。这里有一个方法:

select st.*
from (select st.*, (@rn := @rn + 1) as rn
      from similartable st cross join
          (select @rn := -1) vars
      order by id
     ) st join
     (select st.*, (@rn1 := @rn1 + 1) as rn
      from similartable st cross join
           (select @rn1 := -1) vars
      order by id
     ) st1
     on st1.name = 'Mozart'
where floor(st.rn / 5) = floor(st1.rn / 5)
limit 5;

这将像一个符咒一样工作,但问题是有时,我删除行,ID结果不符合顺序。将有一些行丢失。由于某些原因,它总共只返回4行。但是假设8行。Martin被删除。我想返回5个结果,其中Elvis的名字在行中可见。它将只返回4行,即6行。猫王7。莫扎特9。本杰明10。Geogeit仍然只回来了4排我很糟糕,是的,它现在开始工作了!我不知道你的答案!谢谢!
     11.   Napoleon
     12.   John
     13.   Christopher 
     14.   Michelangelo
     15.   Thomas
select st.*
from similartable st cross join
     (select id from similartable where name = 'Mozart') st1
where floor((st.id - 1)/5) = floor((st1.id - 1)/5)
limit 5;
select st.*
from (select st.*, (@rn := @rn + 1) as rn
      from similartable st cross join
          (select @rn := -1) vars
      order by id
     ) st join
     (select st.*, (@rn1 := @rn1 + 1) as rn
      from similartable st cross join
           (select @rn1 := -1) vars
      order by id
     ) st1
     on st1.name = 'Mozart'
where floor(st.rn / 5) = floor(st1.rn / 5)
limit 5;