在mysql中INSERT IGNORE,INSERT INTO,REPLACE INTO三者都是插入數(shù)據(jù)到mysql數(shù)據(jù)庫的語句,那么這三者之間到底有什么區(qū)別呢?
mysql中常用的三種插入數(shù)據(jù)的語句:
insert into表示插入數(shù)據(jù),數(shù)據(jù)庫會檢查主鍵,如果出現(xiàn)重復會報錯;
replace into表示插入替換數(shù)據(jù),需求表中有PrimaryKey,或者unique索引,如果數(shù)據(jù)庫已經(jīng)存在數(shù)據(jù),則用新數(shù)據(jù)替換,如果沒有數(shù)據(jù)效果則和insert into一樣;
insert ignore表示,如果中已經(jīng)存在相同的記錄,則忽略當前新數(shù)據(jù);下面通過代碼說明之間的區(qū)別,如下:
- create table testtb(
- id int not null primary key,
- name varchar(50),
- age int
- );
- insert into testtb(id,name,age)values(1,"bb",13);
- select * from testtb;
- insert ignore into testtb(id,name,age)values(1,"aa",13);
- select * from testtb;//仍是1,“bb”,13,因為id是主鍵,出現(xiàn)主鍵重復但使用了ignore則錯誤被忽略
- replace into testtb(id,name,age)values(1,"aa",12);
- select * from testtb; //數(shù)據(jù)變?yōu)?,"aa",12
舉例說明,代碼如下:
- insert into
- table 1
- id name
- 1 tb
- 2 zp
- table2
- id(主鍵) name
- 1 tb
- 2 cw
- 3 zp
- insert ignore into table1 select * from table2執(zhí)行結(jié)果為
- table1
- id name
- 1 tb
- 2 zp
- 3 zp
注:如果使用的是insert into 發(fā)現(xiàn)重復的會報錯,而insert ignore into 發(fā)現(xiàn)將要插入的數(shù)據(jù)行中包含唯一索引的字段值已存在,會丟棄掉這行數(shù)據(jù),不做任何處理.
- replace into
- table 1
- id name ps
- 1 tb a
- 2 zp b
- table2
- id(主鍵) name
- 1 tb
- 2 cw
- 3 zp
- replace into table1 select * from table2執(zhí)行結(jié)果為
- table1 //Vevb.com
- id name ps
- 1 tb NULL
- 2 cw NULL
- 3 zp NULL
注:REPLACE發(fā)現(xiàn)重復的先刪除再插入,如果記錄有多個字段,在插入的時候如果有的字段沒有賦值,那么新插入的記錄這些字段為空.
總結(jié):NSERT IGNORE 與INSERT INTO的區(qū)別就是INSERT IGNORE會忽略數(shù)據(jù)庫中已經(jīng)存在 的數(shù)據(jù),如果數(shù)據(jù)庫沒有數(shù)據(jù),就插入新的數(shù)據(jù),如果有數(shù)據(jù)的話就跳過這條數(shù)據(jù),這樣就可以保留數(shù)據(jù)庫中已經(jīng)存在數(shù)據(jù),達到在間隙中插入數(shù)據(jù)的目的.
新聞熱點
疑難解答
圖片精選