2015年8月31日 星期一

MySQL insert into和replace into以及insert ignore


MySQL中常用的三種插入數據的語句:
insert into表示插入數據,資料庫會檢查主鍵,如果出現重複會報錯
replace into表示插入替換數據,需求表中有PrimaryKey,或者unique索引,如果資料庫已經存在數據,則用新數據替換,如果沒有數據效果則和insert into一樣;
insert ignore表示,如果表中如果已經存在相同的記錄,則忽略當前新數據; (不會報錯)

1
2
3
4
5
6
7
8
9
10
11
12
13
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 into testtb(id,name,age)values(1,'bb',13);  -- 第二次會報錯 #1062 - Duplicate entry '1' for key 'PRIMARY'
select * from testtb; 
insert ignore into testtb(id,name,age)values(1,'aa',13);   -- 忽略,不插入
select * from testtb; 
replace into testtb(id,name,age)values(1,"aa",12);  -- 取代
select * from testtb; 


參考資料:
http://qiang106.iteye.com/blog/648467

沒有留言:

張貼留言