在博客「Explain命令可能會修改MySQL數據」瞭解到MySQL中EXPLAIN可能會修改數據,這個現象確實挺讓人意外和震驚的,像SQL Server或Oracle數據庫,查看執行計劃是不會真的執行的SQL語句的,可是MySQL確實有點「古怪」。html
下面,咱們簡單準備一下測試環境數據。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 ;
接下來,咱們測試驗證一下 sql
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」.app
因此這麼說它還不算是一個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())));spa
估計這事只能那些高手深刻代碼研究才能搞清楚這種機制,暫且記錄一下這個現象。code
參考資料:orm
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
https://dev.mysql.com/doc/refman/8.0/en/explain-output.html
https://dev.mysql.com/doc/refman/8.0/en/derived-tables.html