pingcap / tidb

TiDB - the open-source, cloud-native, distributed SQL database designed for modern applications.
https://pingcap.com
Apache License 2.0
37.42k stars 5.85k forks source link

planner: the global binding is not working when using Prepared Statement with "group by hour" #57992

Open qw4990 opened 9 hours ago

qw4990 commented 9 hours ago

Bug Report

Please answer these questions before submitting your issue. Thanks!

1. Minimal reproduce step (Required)

create table t (d datetime);
create global binding for
  select hour(`d`) as `hour` from t group by `hour`
using 
  select hour(`d`) as `hour` from t group by `hour`;

select hour(`d`) as `hour` from t group by `hour`;
select @@last_plan_from_binding;

prepare st from "select hour(`d`) as `hour` from t group by `hour`";
execute st;
select @@last_plan_from_binding;

2. What did you expect to see? (Required)

Both the normal query and the prepared statement can use the global binding.

3. What did you see instead (Required)

mysql> select hour(`d`) as `hour` from t group by `hour`;
Empty set (0.00 sec)

mysql> select @@last_plan_from_binding;
+--------------------------+
| @@last_plan_from_binding |
+--------------------------+
|                        1 |
+--------------------------+
1 row in set (0.00 sec)

mysql> 
mysql> prepare st from "select hour(`d`) as `hour` from t group by `hour`";
Query OK, 0 rows affected (0.00 sec)

mysql> execute st;
Empty set (0.00 sec)

mysql> select @@last_plan_from_binding;
+--------------------------+
| @@last_plan_from_binding |
+--------------------------+
|                        0 |
+--------------------------+
1 row in set (0.01 sec)

4. What is your TiDB version? (Required)

Master

qw4990 commented 9 hours ago

When using Prepared, the normalized query used to match the binding is "select hour ( d ) as hour from test . t group by hour ( d )", but if use normal query, it's "select hour ( d ) as hour from test . t group by hour". So the Prepared process must normalize the query wrongly and change the "group by hour" to "group by hour (d)" and cause this problem. Image