mysql
中常用的三種插入數據的語句:
insert into
表示插入數據,數據庫會檢查主鍵,如果出現重複會報錯;replace into
表示插入替換數據,需求表中有PrimaryKey,或者unique索引,如果數據庫已經存在數據,則用新數據替換,如果沒有數據效果則和insert into
一樣;insert ignore
表示,如果中已經存在相同的記錄,則忽略當前新數據;
下面通過代碼說明之間的區別,如下:
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是主鍵,出現主鍵重複但使用了ignore則錯誤被忽略
replace into testtb(id,name,age)values(1,"aa",12);
select * from testtb; //數據變爲1,"aa",12