diff --git a/executor/aggregate_test.go b/executor/aggregate_test.go index d2e74cf6928fa..f85117ebc5160 100644 --- a/executor/aggregate_test.go +++ b/executor/aggregate_test.go @@ -136,6 +136,8 @@ func (s *testSuite) TestAggregation(c *C) { result.Check(testkit.Rows()) result = tk.MustQuery("select count(*) from t a join t b where a.c < 0") result.Check(testkit.Rows("0")) + result = tk.MustQuery("select sum(b.c), count(b.d), a.c from t a left join t b on a.c = b.d group by b.d order by b.d") + result.Check(testkit.Rows(" 0 4", "8 12 1", "5 2 3")) // This two cases prove that having always resolve name from field list firstly. result = tk.MustQuery("select 1-d as d from t having d < 0 order by d desc") result.Check(testkit.Rows("-1", "-1", "-2", "-2")) diff --git a/plan/physical_plan_builder.go b/plan/physical_plan_builder.go index 3a27a650dd02d..5f297120a40d5 100644 --- a/plan/physical_plan_builder.go +++ b/plan/physical_plan_builder.go @@ -630,17 +630,18 @@ func (p *Aggregation) convert2PhysicalPlanStream(prop *requiredProperty) (*physi props: make([]*columnProp, 0, len(gbyCols)), } for _, pro := range prop.props { - isMatch := false + var matchedCol *expression.Column for i, col := range gbyCols { - if col.ColName.L == pro.col.ColName.L { + if !col.Correlated && col.ColName.L == pro.col.ColName.L { isSortKey[i] = true - isMatch = true + matchedCol = col } } - if !isMatch { + if matchedCol == nil { return info, nil } - newProp.props = append(newProp.props, pro) + // We should add columns in aggregation in order to keep index right. + newProp.props = append(newProp.props, &columnProp{col: matchedCol, desc: pro.desc}) } newProp.sortKeyLen = len(newProp.props) for i, col := range gbyCols {