它并没有真正分页,因为您只是通过有界标识符 (GroupId) 查询数据。如果您知道您的组 ID 并且它们是连续的,那么您可以执行类似的操作。这是使用纯 Go 完成的,您可以轻松地将 gorm 与此结合。
go playground
package main
import (
"fmt"
)
func main() {
for _, q := range queries() {
fmt.Println(q)
}
}
func queries() (out []string) {
groups := []int{10, 20, 30, 40, 50, 60, 70, 80, 90, 100}
for i := 0; i < len(groups); i++ {
var lower, upper int = 0, 0
if i != 0 {
lower = groups[i-1]
}
upper = groups[i]
q := fmt.Sprintf("SELECT * FROM MyTable WHERE GroupId >= %v AND GroupId < %v", lower, upper)
out = append(out, q)
}
return
}
对queries 的调用会打印出应运行的每个查询,以获取每个组中的所有结果。例如:
SELECT * FROM MyTable WHERE GroupId >= 0 AND GroupId < 10
SELECT * FROM MyTable WHERE GroupId >= 10 AND GroupId < 20
SELECT * FROM MyTable WHERE GroupId >= 20 AND GroupId < 30
SELECT * FROM MyTable WHERE GroupId >= 30 AND GroupId < 40
SELECT * FROM MyTable WHERE GroupId >= 40 AND GroupId < 50
SELECT * FROM MyTable WHERE GroupId >= 50 AND GroupId < 60
SELECT * FROM MyTable WHERE GroupId >= 60 AND GroupId < 70
SELECT * FROM MyTable WHERE GroupId >= 70 AND GroupId < 80
SELECT * FROM MyTable WHERE GroupId >= 80 AND GroupId < 90
SELECT * FROM MyTable WHERE GroupId >= 90 AND GroupId < 100
到目前为止,我们假设您已经确切知道要查询的“组存储桶”。相反,如果我们假设我们知道有多少顺序组 (n) 以及每个查询需要多少组 (桶大小 s),我们可以轻松创建一个函数来提供我们应该查询的桶.
go playground
func groups(n, s int) (out []int) {
for i := 0; i <= n; i++ {
if i == 0 {
continue
}
if i%s == 0 || i == n {
out = append(out, i)
}
}
return
}