gorm分页查询count报错 sql no rows in result set
目录
gorm分页查询count报错 sql: no rows in result set
问题
// 用gorm实现分页查询
db.Order("id desc").Limit(10).Offset(1).Find(&List).Count(&totalRows)
//以上查询是没有任何问题的,正常结果
//但是当查询第2页每页查询10条时,如以下语句,这时totalRows为0,且报错 sql: no rows in result set
db.Order("id desc").Limit(10).Offset(10).Find(&List).Count(&totalRows)
注意,Count()查询必须在where条件之后,limit,offset 分页 之前
- 如果写在limit,offset 分页 之前之后,在第二页开始就会报错
sql: no rows in result set
- count也不能太前,否则查询出来的总数将是所有数据总数,非条件过滤后的条数
解决
// 错误db.Order("id desc").Limit(10).Offset(10).Find(&List).Count(&totalRows)
//count应该条件where之后,分页条件之前,如以下,但是结果报错:incorrect table name
db.Order("id desc").Count(&totalRows).Limit(10).Offset(10).Find(&List)
//正确写法:count 写在 limit 前
db.Table("TableName").Order("id desc").Count(&totalRows).Limit(10).Offset(10).Find(&List)
版权声明
未经授权,禁止转载本文章。
如需转载请保留原文链接并注明出处。即视为默认获得授权。
未保留原文链接未注明出处或删除链接将视为侵权,必追究法律责任!
本文原文链接: https://fiveyoboy.com/articles/go-gorm-count-err/
备用原文链接: https://blog.fiveyoboy.com/articles/go-gorm-count-err/