Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

分页查询只有单个列执行查询 在查询SelectCount总数会报错,因为gorm里count处理在mysql会有问题 #68

Closed
bingtianyiyan opened this issue Sep 12, 2023 · 3 comments
Labels
bug Something isn't working

Comments

@bingtianyiyan
Copy link
Contributor

bingtianyiyan commented Sep 12, 2023

gorm对count的执行如果包含distinct 或者列别名会执行报错在mysql,我找了相应的issue :go-gorm/gorm#5821

我的用法:
1694510071205
报错的地方:
func SelectCount[T any](q *QueryCond[T], opts ...OptionFunc) (int64, *gorm.DB) {
var count int64
resultDb := buildCondition(q, opts...)
resultDb.Count(&count) //这里执行会生成sql不正确
return count, resultDb
}

sql生成比方说是生成这样的:SELECT COUNT(Id as id) FROM t_test 这种语法在mysql执行是报错的,
因为gorm里对count逻辑:
1694507712408

所以在不用到类似distinct什么情况下,所有sql一律生成 select count(*) from t_test ,不考虑复杂情况
所以我的解决方案我是想在这边执行Count的时候加个resultDb.Statement.Selects = nil
// SelectCount 根据条件查询记录数量
func SelectCount[T any](q *QueryCond[T], opts ...OptionFunc) (int64, *gorm.DB) {
var count int64
resultDb := buildCondition(q, opts...)
//fix 查询分页数量有列Select只有一个则生成sql不对问题
resultDb.Statement.Selects = nil
resultDb.Count(&count)
return count, resultDb
}

这种感觉也是组件gorm的问题~~~~对各个驱动并没有完全匹配
主要我用的使用列别名转了,如果单个字段,列别名不转的话没有问题,在gorm执行count的时候select count(fieldName) from 表 这样sql执行是正确的。不过总体上gorm的count兼容问题?

@afumu afumu added the bug Something isn't working label Sep 13, 2023
@afumu
Copy link
Member

afumu commented Sep 13, 2023

分析的非常好,如果你感兴趣的话,欢迎你提交pr哈

@bingtianyiyan
Copy link
Contributor Author

分析的非常好,如果你感兴趣的话,欢迎你提交pr哈
我已经提交pr了哈,你看下,然后把自己之前项目增加的cond条件拼接也加进去了

@afumu
Copy link
Member

afumu commented Sep 13, 2023

分析的非常好,如果你感兴趣的话,欢迎你提交pr哈
我已经提交pr了哈,你看下,然后把自己之前项目增加的cond条件拼接也加进去了

在pr下面回复一下 I have read the CLA Document and I hereby sign the CLA 签一下cla

afumu pushed a commit that referenced this issue Sep 13, 2023
@afumu afumu closed this as completed Sep 13, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

2 participants