在博客“Explain命令可能会修改MySQL数据”了解到MySQL中EXPLAIN可能会修改数据,这个现象确实挺让人意外和震惊的,像SQL Server或Oracle数据库,查看执行计划是不会真的执行的SQL语句的,但是MySQL确实有点“古怪”。
下面,我们简单准备一下测试环境数据。
mysql> create table test(id int, name varchar(12));
Query OK, 0 rows affected (0.33 sec)
mysql> insert into test
-> select 1, 'kerry' from dual union all
-> select 2, 'ken' from dual union all
-> select 3, 'jerry' from dual;
Query OK, 3 rows affected (0.08 sec)
Records: 3 Duplicates: 0 Warnings: 0
mysql> DELIMITER &&
mysql> create function cleanup() returns char(50) charset utf8mb4
-> DETERMINISTIC
-> begin
-> delete from test;
-> return 'OK';
-> end &&
Query OK, 0 rows affected (0.07 sec)
mysql> DELIMITER ;
接下来,我们测试验证一下
mysql> select version();
+-----------+
| version() |
+-----------+
| 8.0.18 |
+-----------+
1 row in set (0.00 sec)
mysql> select * from test;
+------+-------+
| id | name |
+------+-------+
| 1 | kerry |
| 2 | ken |
| 3 | jerry |
+------+-------+
3 rows in set (0.00 sec)
mysql> explain select * from (select cleanup()) as t;
+----+-------------+------------+------------+--------+---------------+------+---------+------+------+----------+----------------+
| id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
+----+-------------+------------+------------+--------+---------------+------+---------+------+------+----------+----------------+
| 1 | PRIMARY | <derived2> | NULL | system | NULL | NULL | NULL | NULL | 1 | 100.00 | NULL |
| 2 | DERIVED | NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL | No tables used |
+----+-------------+------------+------------+--------+---------------+------+---------+------+------+----------+----------------+
2 rows in set, 1 warning (0.07 sec)
mysql> select * from test;
Empty set (0.00 sec)
随后翻看官方文档,发现官方文档其实也有简单介绍,只不过一句话带过,不细心的话,还真给忽略了,原文如下:
It is possible in some cases to execute statements that modify data when EXPLAIN SELECT is used with a subquery; for more information, see Section 13.2.11.8, “Derived Tables”.
所以这么说它还不算是一个Bug,也就是说MySQL中使用EXPLAIN查看执行计划时,对应的子查询中调用函数是会执行的。例如,官方文档中还有这么一段描述
This also means that an EXPLAIN SELECT statement such as the one shown here may take a long time to execute because the BENCHMARK() function is executed once for each row in t1:
EXPLAIN SELECT * FROM t1 AS a1, (SELECT BENCHMARK(1000000, MD5(NOW())));
估计这事只能那些高手深入代码研究才能搞清楚这种机制,暂且记录一下这个现象。
参考资料:
https://www.cnblogs.com/abclife/p/14101191.html
https://www.docs4dev.com/docs/zh/mysql/5.7/reference/derived-tables.html
https://www.docs4dev.com/docs/zh/mysql/5.7/reference/explain-output.html