gpt4 book ai didi

mysql - 返回 5 个结果 SQL

转载 作者:行者123 更新时间:2023-11-30 00:02:10 25 4
gpt4 key购买 nike

这对我来说有点难以解释。但我会一步一步告诉你我的目标是什么。我下面有一张类似的表。我的目标是通过仅指定名称来每 5 行返回 5 个结果(LIMIT 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 个结果,其中姓名 Mozart 在行中可见。

这是我想要的结果:(名字莫扎特在接下来的 5 行之后可见)

    6.    Elvis  
7. Mozart
8. Martin
9. Benjamin
10. George

或者假设我想返回 5 个结果,其中名称 Michelangelo 在行中可见。

这是我想要的结果:(名称米开朗基罗在接下来的 5行之后可见)

     11.   Napoleon
12. John
13. Christopher
14. Michelangelo
15. Thomas

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

这是我想要的结果,与第二个示例相同:(名称Christopher在接下来的 5行之后可见)

     11.   Napoleon
12. John
13. Christopher
14. Michelangelo
15. Thomas

最佳答案

您可以通过对 id 进行一些算术来完成此操作:

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;

编辑:

如果 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;

关于mysql - 返回 5 个结果 SQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24932689/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com