问题描述
如何避免在 UPDATE 或者 DELETE 的时候,忘记加 WHERE 条件,导致对数据库的全表数据进行误操作。
问题分析
开启 MySQL 系统变量 sql_safe_updates ,可以捕获没有使用索引,没有使用 WHERE 语句,LIMIT 语句导致的大量的更新或者删除的的操作。
场景模拟
- 开启会话级别的 sql_safe_updates
MySQL [sbtest]> show variables like 'sql_safe_updates';
+------------------+-------+
| Variable_name | Value |
+------------------+-------+
| sql_safe_updates | OFF |
+------------------+-------+
1 row in set (0.002 sec)
MySQL [sbtest]> set session sql_safe_updates=1;
Query OK, 0 rows affected (0.000 sec)
MySQL [sbtest]> show variables like 'sql_safe_updates';
+------------------+-------+
| Variable_name | Value |
+------------------+-------+
| sql_safe_updates | ON |
+------------------+-------+
1 row in set (0.002 sec)
- 模拟删除数据的时候没有加 WHERE 条件和 LIMIT,会捕获异常如下:
MySQL [sbtest]> delete from sbtest1;
ERROR 1175 (HY000): You are using safe update mode and you tried to update a table without a WHERE that uses a KEY column.
- 模拟删除数据的时候有 WHERE 条件,但是 WHERE 条件的列没有索引可用
MySQL [sbtest]> desc sbtest1;
+-------+-----------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+-----------+------+-----+---------+----------------+
| id | int | NO | PRI | NULL | auto_increment |
| k | int | NO | MUL | 0 | |
| c | char(120) | NO | | | |
| pad | char(60) | NO | | | |
+-------+-----------+------+-----+---------+----------------+
4 rows in set (0.001 sec)
MySQL [sbtest]> delete from sbtest1 where c='test';
ERROR 1175 (HY000): You are using safe update mode and you tried to update a table without a WHERE that uses a KEY column.
- 模拟删除使用 limit 语句。
MySQL [sbtest]> delete from sbtest1 limit 2;
Query OK, 2 rows affected (0.002 sec)
参考文档
https://dev.mysql.com/doc/refman/5.7/en/server-system-variables.html 如果您有其他问题,欢迎您联系火山引擎技术支持服务