diff --git a/expression/expression.go b/expression/expression.go index 602383d1e76c1..ba3405796c7fb 100644 --- a/expression/expression.go +++ b/expression/expression.go @@ -454,8 +454,20 @@ func toBool(sc *stmtctx.StatementContext, tp *types.FieldType, eType types.EvalT sVal := buf.GetString(i) if tp.Hybrid() { switch tp.Tp { - case mysql.TypeEnum, mysql.TypeSet: + case mysql.TypeSet, mysql.TypeEnum: fVal = float64(len(sVal)) + if fVal == 0 { + // The elements listed in the column specification are assigned index numbers, beginning + // with 1. The index value of the empty string error value (distinguish from a "normal" + // empty string) is 0. Thus we need to check whether it's an empty string error value when + // `fVal==0`. + for idx, elem := range tp.Elems { + if elem == sVal { + fVal = float64(idx + 1) + break + } + } + } case mysql.TypeBit: var bl types.BinaryLiteral = buf.GetBytes(i) iVal, err := bl.ToInt(sc) diff --git a/expression/integration_test.go b/expression/integration_test.go index 62b6461ed370f..b793d79921fac 100755 --- a/expression/integration_test.go +++ b/expression/integration_test.go @@ -8198,3 +8198,24 @@ func (s *testIntegrationSerialSuite) TestCollationForBinaryLiteral(c *C) { tk.MustQuery("select * from t where col1 not in (0x1B,0x20) order by col1").Check(testkit.Rows("\x1e \xec 6966939640596047133")) tk.MustExec("drop table t") } + +func (s *testIntegrationSuite) Test22717(c *C) { + // For issue 22717 + tk := testkit.NewTestKit(c, s.store) + tk.MustExec("use test") + tk.MustExec("drop table if exists t") + tk.MustExec(`create table t( + a enum('a','','c'), + b enum('0','1','2'), + c set('a','','c'), + d set('0','1','2') + )`) + tk.MustExec("insert into t values(1,1,1,1),(2,2,2,2),(3,3,3,3)") + tk.MustExec("set @@sql_mode = ''") + tk.MustExec("insert into t values('','','','')") + tk.MustQuery("select * from t").Check(testkit.Rows("a 0 a 0", " 1 1", "c 2 a, 0,1", " ")) + tk.MustQuery("select a from t where a").Check(testkit.Rows("a", "", "c", "")) + tk.MustQuery("select b from t where b").Check(testkit.Rows("0", "1", "2")) + tk.MustQuery("select c from t where c").Check(testkit.Rows("a", "", "a,", "")) + tk.MustQuery("select d from t where d").Check(testkit.Rows("0", "1", "0,1")) +}