mirror of https://github.com/go-gorm/gorm.git
Skip order sql when quering with distinct
This commit is contained in:
parent
066abcef40
commit
eb06255b66
4
scope.go
4
scope.go
|
@ -734,7 +734,7 @@ func (scope *Scope) selectSQL() string {
|
|||
}
|
||||
|
||||
func (scope *Scope) orderSQL() string {
|
||||
if len(scope.Search.orders) == 0 || scope.Search.countingQuery {
|
||||
if len(scope.Search.orders) == 0 || scope.Search.ignoreOrderQuery {
|
||||
return ""
|
||||
}
|
||||
|
||||
|
@ -927,7 +927,7 @@ func (scope *Scope) count(value interface{}) *Scope {
|
|||
if query, ok := scope.Search.selects["query"]; !ok || !regexp.MustCompile("(?i)^count(.+)$").MatchString(fmt.Sprint(query)) {
|
||||
scope.Search.Select("count(*)")
|
||||
}
|
||||
scope.Search.countingQuery = true
|
||||
scope.Search.ignoreOrderQuery = true
|
||||
scope.Err(scope.row().Scan(value))
|
||||
return scope
|
||||
}
|
||||
|
|
13
search.go
13
search.go
|
@ -1,6 +1,9 @@
|
|||
package gorm
|
||||
|
||||
import "fmt"
|
||||
import (
|
||||
"fmt"
|
||||
"regexp"
|
||||
)
|
||||
|
||||
type search struct {
|
||||
db *DB
|
||||
|
@ -21,7 +24,7 @@ type search struct {
|
|||
tableName string
|
||||
raw bool
|
||||
Unscoped bool
|
||||
countingQuery bool
|
||||
ignoreOrderQuery bool
|
||||
}
|
||||
|
||||
type searchPreload struct {
|
||||
|
@ -70,7 +73,13 @@ func (s *search) Order(value interface{}, reorder ...bool) *search {
|
|||
return s
|
||||
}
|
||||
|
||||
var distinctSQLRegexp = regexp.MustCompile(`(?i)distinct[^a-z]+[a-z]+`)
|
||||
|
||||
func (s *search) Select(query interface{}, args ...interface{}) *search {
|
||||
if distinctSQLRegexp.MatchString(fmt.Sprint(query)) {
|
||||
s.ignoreOrderQuery = true
|
||||
}
|
||||
|
||||
s.selects = map[string]interface{}{"query": query, "args": args}
|
||||
return s
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue