1. 程式人生 > >MySQL中的insert into類似用法

MySQL中的insert into類似用法

1、insert into
insert into表示插入資料,資料庫會檢查主鍵(PrimaryKey),如果出現重複會報錯。 2、insert ignore into
當插入資料時,如出現錯誤時,如重複資料,將不返回錯誤,只以警告形式返回。所以使用ignore請確保語句本身沒有問題,否則也會被忽略掉。insert ignore表示,如果中已經存在相同的記錄,則忽略當前新資料。
INSERT IGNORE INTO books (name) VALUES ('MySQL Manual') 3、replace into
如果存在primary or unique相同的記錄,則先刪除掉。再插入新記錄。如果記錄有多個欄位,在插入的時候如果有的欄位沒有賦值,那麼新插入的記錄這些欄位為空。
replace into表示插入替換資料,需求表中有PrimaryKey,或者unique索引的話,如果資料庫已經存在資料,則用新資料替換,如果沒有資料效果則和insert into一樣。
REPLACE INTO books SELECT 1, 'MySQL Manual' FROM books 4、on duplicate key update

當primary或者unique重複時,則執行update語句,在原有記錄基礎上,更新指定欄位內容,其它欄位內容保留。如update後為無用語句,如id=id,則同1功能相同,但錯誤不會被忽略掉。
例如,為了實現name重複的資料插入不報錯,可使用一下語句:
INSERT INTO books (name) VALUES ('MySQL Manual') ON duplicate KEY UPDATE id = id; 5、insert … select … where not exist
根據select的條件判斷是否插入,可以不光通過primary 和unique來判斷,也可通過其它條件。例如:
INSERT INTO books (name) SELECT 'MySQL Manual' FROM dual WHERE NOT EXISTS (SELECT id FROM books WHERE id = 1) 注:
如果使用的是insert into 發現重複的會報錯,而insert ignore  into 發現將要插入的資料行中包含唯一索引的欄位值已存在,會丟棄掉這行資料,不做任何處理;REPLACE發現重複的先刪除再插入,如果記錄有多個欄位,在插入的時候如果有的欄位沒有賦值,那麼新插入的記錄這些欄位為空。 示例程式碼:
create table tab_mysqlinsert_tets(
id int not null primary key,
name varchar(50),
age int
);

insert into tab_mysqlinsert_tets(id,name,age)values(1,"bb",13);
select * from tab_mysqlinsert_tets;
insert ignore into tab_mysqlinsert_tets(id,name,age)values(1,"aa",13);
select * from tab_mysqlinsert_tets;//仍是1,“bb”,13,因為id是主鍵,出現主鍵重複但使用了ignore則錯誤被忽略
replace into tab_mysqlinsert_tets(id,name,age)values(1,"aa",12);
select * from tab_mysqlinsert_tets; //資料變為1,"aa",12
insert into tab_mysqlinsert_tets (name) values ('mysql manual') on duplicate key update id = id;
select * from tab_mysqlinsert_tets;
insert into tab_mysqlinsert_tets (id,name) values (0,'mysql manual test') on duplicate key update age = 100;
select * from tab_mysqlinsert_tets;
insert into tab_mysqlinsert_tets (name) select 'mysql manual where no exists' from dual where not exists (select id from tab_mysqlinsert_tets where id = 1);
select * from tab_mysqlinsert_tets;
insert into tab_mysqlinsert_tets (id,name) select 2,'mysql manual where no exists' from dual where not exists (select id from tab_mysqlinsert_tets where id = 2);
select * from tab_mysqlinsert_tets;