本文共 2778 字,大约阅读时间需要 9 分钟。
在MySQL中,如果在update和delete操作中没有加上where条件,数据将会全部修改或删除。这不仅会导致数据丢失,还可能对数据库造成严重影响。因此,MySQL提供了一种安全模式来防止这种误操作。
在连接到数据库后,可以通过以下命令查看当前MySQL安全模式的状态:
mysql> show variables like 'sql_safe_updates';
例如,查询结果可能如下:
mysql> show variables like 'sql_safe_updates';+------------------+-------+| Variable_name | Value |+------------------+-------+| sql_safe_updates | ON |+------------------+-------+1 row in set (0.00 sec)
如上所示,当sql_safe_updates的值为ON时,安全模式已开启。要开启或关闭安全模式,可以使用以下命令:
mysql> set sql_safe_updates=1; //安全模式打开状态
mysql> set sql_safe_updates=0; //安全模式关闭状态
以下是安全模式下update操作的几种常见情况:
无where条件的update
mysql> update users set status=1;
错误信息:You are using safe update mode and you tried to update a table without a WHERE that uses a KEY column
解释:由于没有where条件且没有索引可用,因此操作失败。
无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限制,操作成功。
使用非索引字段作为条件进行更新
mysql> update users set status=1 where reg_time>'2018-01-01 00:00:00';
错误信息:You are using safe update mode and you tried to update a table without a WHERE that uses a KEY column
解释:条件字段不是索引字段且没有limit限制,因此操作失败。
使用非索引字段作为条件并且加入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限制,操作成功。
使用索引字段作为条件并且不加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
解释:条件字段是索引字段,因此操作成功。
以下是安全模式下delete操作的几种常见情况:
无where条件的delete
mysql> delete from users;
错误信息:You are using safe update mode and you tried to update a table without a WHERE that uses a KEY column
解释:没有where条件且没有索引可用,因此操作失败。
非索引键进行条件删除
mysql> delete from users where reg_time='2018-06-28 17:35:37';
错误信息:You are using safe update mode and you tried to update a table without a WHERE that uses a KEY column
解释:条件字段不是索引键,因此操作失败。
非索引键作为条件并且加入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限制,操作成功。
使用索引键并且不加limit限制进行删除
mysql> delete from users where user_id=100000;
成功信息:Query OK, 1 row affected (0.01 sec)
解释:条件字段是索引键,因此操作成功。
加入limit但是不使用where条件删除
mysql> delete from users limit 1;
错误信息: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和delete操作需要满足以下条件才能执行成功:
update操作:
delete操作:
转载地址:http://nkdfk.baihongyu.com/