Fix Count in mssql for SQL with group

This commit is contained in:
Jinzhu 2018-02-11 09:16:10 +08:00
parent 85774eb9da
commit fd15156d39
2 changed files with 11 additions and 2 deletions

View File

@ -430,6 +430,15 @@ func TestCount(t *testing.T) {
if count1 != 1 || count2 != 3 {
t.Errorf("Multiple count in chain")
}
var count3 int
if err := DB.Model(&User{}).Where("name in (?)", []string{user2.Name, user2.Name, user3.Name}).Group("id").Count(&count3).Error; err != nil {
t.Errorf("Not error should happen, but got %v", err)
}
if count3 != 2 {
t.Errorf("Should get correct count, but got %v", count3)
}
}
func TestNot(t *testing.T) {

View File

@ -951,8 +951,8 @@ 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(*) ")
scope.Search.group += " ) AS count"
scope.Search.Select("count(*) FROM ( SELECT count(*) as name ")
scope.Search.group += " ) AS count_table"
} else {
scope.Search.Select("count(*)")
}