From 33261f24bbcd38bfd2b4c5a11a2b02dcf4404cd8 Mon Sep 17 00:00:00 2001 From: Yuanjia Zhang Date: Wed, 9 Nov 2022 17:49:51 +0800 Subject: [PATCH] planner: outer join elimination doesn't consider the ORDER BY items from the agg func (#38380) (#39024) close pingcap/tidb#18216 --- planner/core/integration_test.go | 13 +++++++++++++ planner/core/rule_join_elimination.go | 3 +++ 2 files changed, 16 insertions(+) diff --git a/planner/core/integration_test.go b/planner/core/integration_test.go index 87f7642be569c..3addc331cdba4 100644 --- a/planner/core/integration_test.go +++ b/planner/core/integration_test.go @@ -1538,6 +1538,19 @@ func (s *testIntegrationSuite) TestIndexMergeHint4CNF(c *C) { } } +func (s *testIntegrationSuite) TestOuterJoinEliminationForIssue18216(c *C) { + tk := testkit.NewTestKit(c, s.store) + tk.MustExec("use test") + tk.MustExec("drop table if exists t1, t2;") + tk.MustExec("create table t1 (a int, c int);") + tk.MustExec("insert into t1 values (1, 1), (1, 2), (2, 3), (2, 4);") + tk.MustExec("create table t2 (a int, c int);") + tk.MustExec("insert into t2 values (1, 1), (1, 2), (2, 3), (2, 4);") + // The output might be unstable. + tk.MustExec("select group_concat(c order by (select group_concat(c order by a) from t2 where a=t1.a)) from t1; ") + tk.MustQuery("select group_concat(c order by (select group_concat(c order by c) from t2 where a=t1.a), c desc) from t1;").Check(testkit.Rows("2,1,4,3")) +} + func (s *testIntegrationSuite) TestInvisibleIndex(c *C) { tk := testkit.NewTestKit(c, s.store) diff --git a/planner/core/rule_join_elimination.go b/planner/core/rule_join_elimination.go index 025d538aafbc3..495b8d989e628 100644 --- a/planner/core/rule_join_elimination.go +++ b/planner/core/rule_join_elimination.go @@ -206,6 +206,9 @@ func (o *outerJoinEliminator) doOptimize(p LogicalPlan, aggCols []*expression.Co for _, expr := range aggDesc.Args { parentCols = append(parentCols, expression.ExtractColumns(expr)...) } + for _, byItem := range aggDesc.OrderByItems { + parentCols = append(parentCols, expression.ExtractColumns(byItem.Expr)...) + } } default: parentCols = append(parentCols[:0], p.Schema().Columns...)