当前位置:Gxlcms > 数据库问题 > MYSQL的安全模式:sql_safe_updates介绍

MYSQL的安全模式:sql_safe_updates介绍

时间:2021-07-01 10:21:17 帮助过:18人阅读

上面查询命令实例表示当前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子句中列可以不是索引列)

MYSQL的安全模式:sql_safe_updates介绍

标签:str   查询   mat   连接   字段   without   column   限制   使用   

人气教程排行