diff --git a/expression/integration_test.go b/expression/integration_test.go index 3efa93eff5d13..6525120d59eb0 100644 --- a/expression/integration_test.go +++ b/expression/integration_test.go @@ -2208,6 +2208,22 @@ func TestAggregationBuiltinJSONObjectAgg(t *testing.T) { result.Check(testkit.Rows(`{"first": "json_objectagg_test"}`)) result = tk.MustQuery("select json_objectagg(a, null) from t group by a order by a;") result.Check(testkit.Rows(`{"1": null}`)) + + // For issue: https://github.com/pingcap/tidb/issues/39806 + // Optimization shouldn't rewrite the flag of `castStringAsJson`. + tk.MustQuery(` + select a from ( + select JSON_OBJECT('number', number, 'name', name) 'a' from + ( + select 1 as number, 'name-1' as name union + (select 2, 'name-2' ) union + (select 3, 'name-3' ) union + (select 4, 'name-4' ) union + (select 5, 'name-5' ) union + (select 6, 'name-2' ) + ) temp1 + ) temp + where a ->> '$.number' = 1`).Check(testkit.Rows(`{"name": "name-1", "number": 1}`)) } func TestOtherBuiltin(t *testing.T) { diff --git a/expression/util.go b/expression/util.go index 22637d1b8617f..e19ec047e43d0 100644 --- a/expression/util.go +++ b/expression/util.go @@ -427,8 +427,10 @@ func ColumnSubstituteImpl(expr Expression, schema *Schema, newExprs []Expression return substituted, hasFail, v } if substituted { + flag := v.RetType.GetFlag() e := BuildCastFunction(v.GetCtx(), newArg, v.RetType) e.SetCoercibility(v.Coercibility()) + e.GetType().SetFlag(flag) return true, false, e } return false, false, v