在应用 BUG或者 DBA误操作的情况下,会发生对全表进行更新:update delete 的情况。MySQL提供 sql_safe_updates 来限制次操作。
set sql_safe_updates = 1;
设置之后,会限制update delete 中不带 where 条件的SQL 执行,较严格。会对已有线上环境带来不利影响。对新系统、应用做严格审核,可以确保不会发生全表更新的问题。
CREATE TABLE working.test01 (id INT NOT NULL AUTO_INCREMENT,NAME VARCHAR(20),age INT,gmt_created DATETIME,PRIMARY KEY(id)); insert into test01(name,age,gmt_created) values('xiaowang',2,now()); insert into test01(name,age,gmt_created) values('huahua',5,now()); insert into test01(name,age,gmt_created) values('gougou',9,now()); insert into test01(name,age,gmt_created) values('heihei',12,now()); insert into test01(name,age,gmt_created) values('baibai',134,now()); # 过滤字段上没有索引updateupdate test01 set name = 'xiaoxiao' where age = 2 ;ERROR 1175 (HY000): You are using safe update mode and you tried to update a table without a WHERE that uses a KEY column# 全表更新update test01 set name = 'xiaoxiao';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的更新update test01 set name = 'xia' limit 1;Query OK, 1 row affected (0.00 sec)Rows matched: 1 Changed: 1 Warnings: 0# 新增索引create index idx_age on test01(age);update test01 set name = 'xiaoxiao' where age = 2;Query OK, 1 row affected (0.01 sec)Rows matched: 1 Changed: 1 Warnings: 0update test01 set name = 'hhh' where age = 9 limit 10;Query OK, 1 row affected (0.00 sec)Rows matched: 1 Changed: 1 Warnings: 0alter table test01 drop index idx_age;create index idx_age_name on test01(age,name);update test01 set age= 100 where name = 'hhh';ERROR 1175 (HY000): You are using safe update mode and you tried to update a table without a WHERE that uses a KEY columnupdate test01 set age= 100 where name = 'hhh' limit 10;Query OK, 1 row affected (0.00 sec)Rows matched: 1 Changed: 1 Warnings: 0
由此,update 时,在没有 where 条件或者where 后不是索引字段时,必须使用 limit ;在有 where 条件时,为索引字段
本文为云栖社区原创内容,未经允许不得转载,如需转载请发送邮件至yqeditor@list.alibaba-inc.com;如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件至:yqgroup@service.aliyun.com 进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容。

用云栖社区APP,舒服~
【云栖快讯】他,一路保送,但可能不是你想象中的学霸; 他,曾是微软最年轻的技术管理者,挑战带领跨国团队; 他,后来加入阿里,成为阿里西雅图分部的第22名员工; 他,就是阿里通用计算平台负责人关涛! 云栖社区通过短视频,为你揭晓他的成长和开发计算平台的经历,以及他对未来的展望! 详情请点击
注:本文内容来自互联网,旨在为开发者提供分享、交流的平台。如有涉及文章版权等事宜,请你联系站长进行处理。