Skip to content

Commit 415ee2c

Browse files
committed
add correlated subquery columns to groupby select dependencies
1 parent 3d7fa0e commit 415ee2c

File tree

2 files changed

+24
-3
lines changed

2 files changed

+24
-3
lines changed

sql/planbuilder/aggregates.go

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -224,8 +224,8 @@ func (b *Builder) buildAggregation(fromScope, projScope *scope, groupingCols []s
224224
default:
225225
}
226226

227-
// projection dependencies -> table cols needed above
228-
transform.InspectExpr(col.scalar, func(e sql.Expression) bool {
227+
var findSelectDeps func(sql.Expression) bool
228+
findSelectDeps = func(e sql.Expression) bool {
229229
switch e := e.(type) {
230230
case *expression.GetField:
231231
colName := strings.ToLower(e.String())
@@ -241,10 +241,19 @@ func (b *Builder) buildAggregation(fromScope, projScope *scope, groupingCols []s
241241
} else if isAliasDep && !inAlias {
242242
aliasDeps[exprStr] = false
243243
}
244+
case *plan.Subquery:
245+
e.Correlated().ForEach(func(colId sql.ColumnId) {
246+
if correlated, found := projScope.parent.getCol(colId); found {
247+
findSelectDeps(correlated.scalarGf())
248+
}
249+
})
244250
default:
245251
}
246252
return false
247-
})
253+
}
254+
255+
// projection dependencies -> table cols needed above
256+
transform.InspectExpr(col.scalar, findSelectDeps)
248257
}
249258
for _, e := range fromScope.extraCols {
250259
// accessory cols used by ORDER_BY, HAVING

sql/planbuilder/scope.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,18 @@ func (s *scope) resolveColumn(db, table, col string, checkParent, chooseFirst bo
149149
return c, true
150150
}
151151

152+
// getCol gets a scopeColumn based on a columnId
153+
func (s *scope) getCol(colId sql.ColumnId) (scopeColumn, bool) {
154+
if s.colset.Contains(colId) {
155+
for _, c := range s.cols {
156+
if sql.ColumnId(c.id) == colId {
157+
return c, true
158+
}
159+
}
160+
}
161+
return scopeColumn{}, false
162+
}
163+
152164
func (s *scope) hasTable(table string) bool {
153165
_, ok := s.tables[strings.ToLower(table)]
154166
if ok {

0 commit comments

Comments
 (0)