diff --git a/executor/show_stats.go b/executor/show_stats.go index c63286e6a8337..b5410c360fdcd 100644 --- a/executor/show_stats.go +++ b/executor/show_stats.go @@ -82,6 +82,10 @@ func (e *ShowExec) appendTableForStatsHistograms(dbName, tblName, partitionName return } for _, col := range statsTbl.Columns { + // Pass a nil StatementContext to avoid column stats being marked as needed. + if col.IsInvalid(nil, false) { + continue + } e.histogramToRow(dbName, tblName, partitionName, col.Info.Name.O, 0, col.Histogram, col.AvgColSize(statsTbl.Count)) } for _, idx := range statsTbl.Indices { diff --git a/executor/show_stats_test.go b/executor/show_stats_test.go index dcb9139073b72..2786ac65498ef 100644 --- a/executor/show_stats_test.go +++ b/executor/show_stats_test.go @@ -40,13 +40,26 @@ func (s *testSuite1) TestShowStatsHistograms(c *C) { tk.MustExec("drop table if exists t") tk.MustExec("create table t (a int, b int)") tk.MustExec("analyze table t") - result := tk.MustQuery("show stats_histograms").Sort() + result := tk.MustQuery("show stats_histograms") + c.Assert(len(result.Rows()), Equals, 0) + tk.MustExec("insert into t values(1,1)") + tk.MustExec("analyze table t") + result = tk.MustQuery("show stats_histograms").Sort() c.Assert(len(result.Rows()), Equals, 2) c.Assert(result.Rows()[0][3], Equals, "a") c.Assert(result.Rows()[1][3], Equals, "b") result = tk.MustQuery("show stats_histograms where column_name = 'a'") c.Assert(len(result.Rows()), Equals, 1) c.Assert(result.Rows()[0][3], Equals, "a") + + tk.MustExec("drop table t") + tk.MustExec("create table t(a int, b int, c int, index idx_b(b), index idx_c_a(c, a))") + tk.MustExec("insert into t values(1,null,1),(2,null,2),(3,3,3),(4,null,4),(null,null,null)") + res := tk.MustQuery("show stats_histograms where table_name = 't'") + c.Assert(len(res.Rows()), Equals, 0) + tk.MustExec("analyze table t index idx_b") + res = tk.MustQuery("show stats_histograms where table_name = 't' and column_name = 'idx_b'") + c.Assert(len(res.Rows()), Equals, 1) } func (s *testSuite1) TestShowStatsBuckets(c *C) { diff --git a/statistics/table.go b/statistics/table.go index 7f59926fd1d56..2110a13bdbd06 100644 --- a/statistics/table.go +++ b/statistics/table.go @@ -351,7 +351,7 @@ func (c *Column) IsInvalid(sc *stmtctx.StatementContext, collPseudo bool) bool { if collPseudo && c.NotAccurate() { return true } - if c.NDV > 0 && c.Len() == 0 { + if c.NDV > 0 && c.Len() == 0 && sc != nil { sc.SetHistogramsNotLoad() histogramNeededColumns.insert(tableColumnID{tableID: c.PhysicalID, columnID: c.Info.ID}) }