Skip to content

Commit 540d7a2

Browse files
authored
Merge pull request #1398 from renom/master
Count from subquery if query uses HAVING or GROUP BY
2 parents bc92201 + cb3a21b commit 540d7a2

File tree

1 file changed

+17
-6
lines changed

1 file changed

+17
-6
lines changed

queries/query_builders.go

Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,14 @@ func buildSelectQuery(q *Query) (*bytes.Buffer, []interface{}) {
5353
writeComment(q, buf)
5454
writeCTEs(q, buf, &args)
5555

56+
hasHaving := len(q.having) != 0
57+
hasGroupBy := len(q.groupBy) != 0
58+
hasSimpleCount := q.count && !hasHaving && !hasGroupBy
59+
hasComplexCount := q.count && (hasHaving || hasGroupBy)
60+
if hasComplexCount {
61+
buf.WriteString("SELECT COUNT(*) FROM (")
62+
}
63+
5664
buf.WriteString("SELECT ")
5765

5866
if q.dialect.UseTopClause {
@@ -61,7 +69,7 @@ func buildSelectQuery(q *Query) (*bytes.Buffer, []interface{}) {
6169
}
6270
}
6371

64-
if q.count {
72+
if hasSimpleCount {
6573
buf.WriteString("COUNT(")
6674
}
6775

@@ -70,28 +78,28 @@ func buildSelectQuery(q *Query) (*bytes.Buffer, []interface{}) {
7078
hasDistinct := q.distinct != ""
7179
if hasDistinct {
7280
buf.WriteString("DISTINCT ")
73-
if q.count {
81+
if hasSimpleCount {
7482
buf.WriteString("(")
7583
}
7684
buf.WriteString(q.distinct)
77-
if q.count {
85+
if hasSimpleCount {
7886
buf.WriteString(")")
7987
}
80-
} else if hasJoins && hasSelectCols && !q.count {
88+
} else if hasJoins && hasSelectCols && !hasSimpleCount {
8189
selectColsWithAs := writeAsStatements(q)
8290
// Don't identQuoteSlice - writeAsStatements does this
8391
buf.WriteString(strings.Join(selectColsWithAs, ", "))
8492
} else if hasSelectCols {
8593
buf.WriteString(strings.Join(strmangle.IdentQuoteSlice(q.dialect.LQ, q.dialect.RQ, q.selectCols), ", "))
86-
} else if hasJoins && !q.count {
94+
} else if hasJoins && !hasSimpleCount {
8795
selectColsWithStars := writeStars(q)
8896
buf.WriteString(strings.Join(selectColsWithStars, ", "))
8997
} else {
9098
buf.WriteByte('*')
9199
}
92100

93101
// close SQL COUNT function
94-
if q.count {
102+
if hasSimpleCount {
95103
buf.WriteByte(')')
96104
}
97105

@@ -133,6 +141,9 @@ func buildSelectQuery(q *Query) (*bytes.Buffer, []interface{}) {
133141

134142
writeModifiers(q, buf, &args)
135143

144+
if hasComplexCount {
145+
buf.WriteByte(')')
146+
}
136147
buf.WriteByte(';')
137148
return buf, args
138149
}

0 commit comments

Comments
 (0)