Merge pull request #2324 from xwjdsh/bugfix/having-on-count

fix the case that using Having on Count
This commit is contained in:
Emir Beganović 2019-04-14 11:40:45 +04:00 committed by GitHub
commit 9df293e681
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 35 additions and 2 deletions

View File

@ -1059,6 +1059,32 @@ func TestBlockGlobalUpdate(t *testing.T) {
}
}
func TestCountWithHaving(t *testing.T) {
db := DB.New()
db.Delete(User{})
defer db.Delete(User{})
DB.Create(getPreparedUser("user1", "pluck_user"))
DB.Create(getPreparedUser("user2", "pluck_user"))
user3:=getPreparedUser("user3", "pluck_user")
user3.Languages=[]Language{}
DB.Create(user3)
var count int
err:=db.Model(User{}).Select("users.id").
Joins("LEFT JOIN user_languages ON user_languages.user_id = users.id").
Joins("LEFT JOIN languages ON user_languages.language_id = languages.id").
Group("users.id").Having("COUNT(languages.id) > 1").Count(&count).Error
if err != nil {
t.Error("Unexpected error on query count with having")
}
if count!=2{
t.Error("Unexpected result on query count with having")
}
}
func BenchmarkGorm(b *testing.B) {
b.N = 2000
for x := 0; x < b.N; x++ {

View File

@ -1007,8 +1007,15 @@ func (scope *Scope) pluck(column string, value interface{}) *Scope {
func (scope *Scope) count(value interface{}) *Scope {
if query, ok := scope.Search.selects["query"]; !ok || !countingQueryRegexp.MatchString(fmt.Sprint(query)) {
if len(scope.Search.group) != 0 {
scope.Search.Select("count(*) FROM ( SELECT count(*) as name ")
scope.Search.group += " ) AS count_table"
if len(scope.Search.havingConditions) != 0 {
scope.prepareQuerySQL()
scope.Search = &search{}
scope.Search.Select("count(*)")
scope.Search.Table(fmt.Sprintf("( %s ) AS count_table", scope.SQL))
} else {
scope.Search.Select("count(*) FROM ( SELECT count(*) as name ")
scope.Search.group += " ) AS count_table"
}
} else {
scope.Search.Select("count(*)")
}