From 1b5c1e69d9c6577c7ed5c2975bd83dc227361eac Mon Sep 17 00:00:00 2001 From: ti-srebot <66930949+ti-srebot@users.noreply.github.com> Date: Fri, 3 Sep 2021 09:32:14 +0800 Subject: [PATCH] planner: fix tablesample 'order by' clause from partitioned table (#27383) (#27412) --- executor/sample_test.go | 11 +++++++++++ planner/core/find_best_task.go | 6 ++++++ 2 files changed, 17 insertions(+) diff --git a/executor/sample_test.go b/executor/sample_test.go index 42aed46448881..44ce8ccbb7e30 100644 --- a/executor/sample_test.go +++ b/executor/sample_test.go @@ -200,6 +200,17 @@ func (s *testTableSampleSuite) TestTableSampleWithPartition(c *C) { c.Assert(len(rows), Equals, 0) rows = tk.MustQuery("select * from t partition (p1) tablesample regions();").Rows() c.Assert(len(rows), Equals, 1) + + // Test https://github.com/pingcap/tidb/issues/27349. + tk.MustExec("drop table if exists t;") + tk.MustExec(`create table t (a int, b int, unique key idx(a)) partition by range (a) ( + partition p0 values less than (0), + partition p1 values less than (10), + partition p2 values less than (30), + partition p3 values less than (maxvalue));`) + tk.MustExec("insert into t values (2, 2), (31, 31), (12, 12);") + tk.MustQuery("select _tidb_rowid from t tablesample regions() order by _tidb_rowid;"). + Check(testkit.Rows("1", "2", "3")) // The order of _tidb_rowid should be correct. } func (s *testTableSampleSuite) TestTableSampleGeneratedColumns(c *C) { diff --git a/planner/core/find_best_task.go b/planner/core/find_best_task.go index 767f91301d65e..85d5887a78094 100644 --- a/planner/core/find_best_task.go +++ b/planner/core/find_best_task.go @@ -1608,6 +1608,12 @@ func (ds *DataSource) convertToSampleTable(prop *property.PhysicalProperty, cand if !prop.IsEmpty() && !candidate.isMatchProp { return invalidTask, nil } + if candidate.isMatchProp { + // TableSample on partition table can't keep order. + if ds.tableInfo.GetPartitionInfo() != nil { + return invalidTask, nil + } + } p := PhysicalTableSample{ TableSampleInfo: ds.SampleInfo, TableInfo: ds.table,