MYSQL的安全模式:sql_safe_updates介绍

什么是安全模式

在mysql中,如果在update和delete没有加上where条件,数据将会全部修改。不只是初识mysql的开发者会遇到这个问题,工作有一定经验的工程师难免也会忘记写入where条件。为了避免失误造成的数据全部修改和删除,可开启mysql的安全模式。

安全模式的开启与关闭

连接到数据库后,查看当前mysql的安全模式的状态

mysql> show variables like 'sql_safe_updates';
+------------------+-------+
| Variable_name    | Value |
+------------------+-------+
| sql_safe_updates | ON    |
+------------------+-------+
1 row in set (0.00 sec)

上面查询命令实例表示当前mysql处于安全模式打开的状态。
set sql_safe_updates=1; //安全模式打开状态
set sql_safe_updates=0; //安全模式关闭状态

在update操作中:当where条件中列(column)没有索引可用且无limit限制时会拒绝更新。where条件为常量且无limit限制时会拒绝更新。

在delete操作中: 当①where条件为常量,②或where条件为空,③或where条件中 列(column)没有索引可用且无limit限制时拒绝删除。

安全模式UPDATE操作实例

1、无where条件的update

mysql> update users set status=1;
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条件作为主键。

2、无where条件但是有limit的update

mysql> update users set status=1 limit 1;
Query OK, 0 rows affected (0.00 sec)
Rows matched: 1  Changed: 0  Warnings: 0

操作成功,虽然没有where条件,但是加入了limit限制。

3、使用非索引字段作为条件进行更新

mysql> update users set status=1 where reg_time>'2018-01-01 00:00:00';
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限制。

4、使用非索引字段作为条件并且加入limit进行更新

mysql> update users set status=1 where reg_time>'2018-01-01 00:00:00' limit 10;
Query OK, 0 rows affected (0.01 sec)
Rows matched: 10  Changed: 0  Warnings: 0

操作成功,虽然条件字段不是索引字段,但是有加入limit限制,所以执行成功。

5、使用索引字段作为条件并且不加入limit进行更新

mysql> update users set status=1 where phone_num='13800138000';
Query OK, 0 rows affected (0.00 sec)
Rows matched: 1  Changed: 0  Warnings: 0

操作成功,虽然没有加入limit限制,但是条件字段为索引字段,所以执行成功。

安全模式DELETE操作实例

1、无where条件的delete

mysql> delete from users;
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条件,直接不行。

2、非索引键进行条件删除

mysql> delete from users where reg_time='2018-06-28 17:35:37';
ERROR 1175 (HY000): You are using safe update mode and you tried to update a table without a WHERE that uses a KEY column

操作失败,因为reg_time字段不是索引键。

3、非索引键作为条件并且加入limit进行删除

mysql> delete from users where reg_time='2018-06-28 17:35:37' limit 1;
Query OK, 1 row affected (0.00 sec)

操作成功,即使不是索引键,因为加入了limit。

4、使用索引键并且不加limit限制进行删除。

mysql> delete from users where user_id=100000;
Query OK, 1 row affected (0.01 sec)

操作成功,因为user_id是索引键。

5、加入limit但是不使用where条件删除。

mysql> delete from users limit 1;
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检索条件。

总结

如果设置了sql_safe_updates=1,那么update语句必须满足如下条件之一才能执行成功

1)使用where子句,并且where子句中列必须为prefix索引列
2)使用limit
3)同时使用where子句和limit(此时where子句中列可以不是索引列)

delete语句必须满足如下条件之一才能执行成功
1)使用where子句,并且where子句中列必须为prefix索引列
2)同时使用where子句和limit(此时where子句中列可以不是索引列)

posted on 2019-04-26 14:34  枫飞飞  阅读(4022)  评论(2编辑  收藏  举报