diff --git a/expression/integration_test.go b/expression/integration_test.go index b2f5562538dd4..a6204308189b6 100755 --- a/expression/integration_test.go +++ b/expression/integration_test.go @@ -7114,3 +7114,16 @@ func (s *testIntegrationSerialSuite) TestIssue17063(c *C) { tk.MustQuery(`select collation(lag(b, 1, 'B') over w) from t window w as (order by b);`).Check(testkit.Rows("utf8mb4_general_ci", "utf8mb4_general_ci")) tk.MustQuery(`select coercibility(lag(b, 1, 'B') over w) from t window w as (order by b);`).Check(testkit.Rows("2", "2")) } + +func (s *testIntegrationSuite) TestIssue19504(c *C) { + tk := testkit.NewTestKit(c, s.store) + tk.MustExec("use test") + tk.MustExec("drop table if exists t1;") + tk.MustExec("create table t1 (c_int int, primary key (c_int));") + tk.MustExec("insert into t1 values (1), (2), (3);") + tk.MustExec("drop table if exists t2;") + tk.MustExec("create table t2 (c_int int, primary key (c_int));") + tk.MustExec("insert into t2 values (1);") + tk.MustQuery("select (select count(c_int) from t2 where c_int = t1.c_int) c1, (select count(1) from t2 where c_int = t1.c_int) c2 from t1;"). + Check(testkit.Rows("1 1", "0 0", "0 0")) +} diff --git a/planner/core/rule_decorrelate.go b/planner/core/rule_decorrelate.go index 1243de5a841a0..956d651f660ff 100644 --- a/planner/core/rule_decorrelate.go +++ b/planner/core/rule_decorrelate.go @@ -185,9 +185,19 @@ func (s *decorrelateSolver) optimize(ctx context.Context, p LogicalPlan) (Logica outerCol.RetType = first.RetTp outerColsInSchema = append(outerColsInSchema, outerCol) } - newAggFuncs = append(newAggFuncs, agg.AggFuncs...) - agg.AggFuncs = newAggFuncs apply.SetSchema(expression.MergeSchema(expression.NewSchema(outerColsInSchema...), innerPlan.Schema())) + resetNotNullFlag(apply.schema, outerPlan.Schema().Len(), apply.schema.Len()) + + for i, aggFunc := range agg.AggFuncs { + if idx := apply.schema.ColumnIndex(aggFunc.Args[0].(*expression.Column)); idx != -1 { + desc, err := aggregation.NewAggFuncDesc(agg.ctx, agg.AggFuncs[i].Name, []expression.Expression{apply.schema.Columns[idx]}, false) + if err != nil { + return nil, err + } + newAggFuncs = append(newAggFuncs, desc) + } + } + agg.AggFuncs = newAggFuncs np, err := s.optimize(ctx, p) if err != nil { return nil, err