mysql利用參數(shù)sql_safe_updates限制update/delete范圍詳解
大家應(yīng)該都知道,我們?cè)趍ysql運(yùn)維中出現(xiàn)過不少因?yàn)閡pdate/delete條件錯(cuò)誤導(dǎo)致數(shù)據(jù)被誤更新或者刪除的case,為避免類似問題的發(fā)生,可以用sql_safe_updates參數(shù)來對(duì)update/delete做限制。這個(gè)參數(shù)設(shè)置為on后,可防止因程序bug或者DBA手工誤操作導(dǎo)致的整個(gè)表被更新或者刪除的情況。下面話不多說了,來一起看看詳細(xì)的介紹吧。
設(shè)置這個(gè)參數(shù)時(shí)需要注意一下幾點(diǎn):
a、設(shè)置前需要確認(rèn)程序中所有的update和delete都符合sql_safe_updates的限制規(guī)范,不然程序會(huì)報(bào)錯(cuò)。
b、5.0,5.1都是session級(jí)別的,5.6是global&session級(jí)別;低版本的數(shù)據(jù)庫(kù)只能在程序創(chuàng)建session時(shí)設(shè)置帶上set sql_safe_updates=on;高版本的數(shù)據(jù)庫(kù)可以直接set global set sql_safe_updates=on,設(shè)置完成后讓程序重連后生效。
限制規(guī)范:
示例表結(jié)構(gòu):
CREATE TABLE `delay_monitor` ( `id` int(11) NOT NULL, `Ftime` datetime DEFAULT NULL, `Fgtid` varchar(128) NOT NULL DEFAULT '', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin
1、update
a、報(bào)錯(cuò)條件:不帶where、帶where無索引、where條件為常量
不帶where:update delay_monitor set Ftime=now();
帶where無索引:update delay_monitor set Ftime=now() where Fgtid='test';
where條件為常量:update delay_monitor set Ftime=now() where 1;
b、執(zhí)行條件:帶where帶索引、不帶where+帶limit、帶where無索引+limit、帶where有索引+limit、where條件為常量+limit
帶where帶索引:update delay_monitor set Ftime=now() where id=2;
不帶where+帶limit: update delay_monitor set Ftime=now() limit 1;
帶where無索引+limit:update delay_monitor set Ftime=now() where Fgtid='test' limit 1;
帶where有索引+limit:update delay_monitor set Ftime=now() where id =2 limit1;
where條件為常量+limit:update delay_monitor set Ftime=now() where 1 limit 1;
2、delete
相對(duì)于update,delelte的限制會(huì)更為嚴(yán)格;where條件為常量或者為空,將不予執(zhí)行。
a、報(bào)錯(cuò)條件:不帶where、帶where無索引、不帶where+帶limit、where條件為常量、where條件為常量+limit
不帶where:delete delay_monitor set Ftime=now();
帶where無索引:delete delay_monitor set Ftime=now() where Fgtid='test';
不帶where+帶limit: delete delay_monitor set Ftime=now() limit 1;
where條件為常量:delete delay_monitor set Ftime=now() where 1;
where條件為常量+limit:delete delay_monitor set Ftime=now() where 1 limit 1;
b、執(zhí)行條件:帶where帶索引、帶where無索引+limit、帶where有索引+limt
帶where帶索引:delete delay_monitor set Ftime=now() where id=2;
帶where無索引+limit:delete delay_monitor set Ftime=now() where Fgtid='test' limit 1;
帶where有索引+limit:delete delay_monitor set Ftime=now() where id =2 limit1;
總結(jié)如下表:key表示所有、const表示常量
| 操作 | no where | where key | where nokey | limit | where nokey+limit | where key+limit | where const | where const+limit |
| delete | NO | YES | NO | NO | YES | YES | NO | NO |
| update | NO | YES | NO | YES | YES | YES | NO | YES |
總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,如果有疑問大家可以留言交流,謝謝大家對(duì)本站的支持。
版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請(qǐng)保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非maisonbaluchon.cn所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場(chǎng),如有內(nèi)容涉嫌侵權(quán),請(qǐng)聯(lián)系alex-e#qq.com處理。
關(guān)注官方微信