標籤:
今天在編程的時候,學習了replace into的用法,真的很好用,是insert into的增強版。在向表中插入資料時,我們經常會遇到這樣的情況:1、首先判斷資料是否存在;2、如果不存在,則插入;3、如果存在,則更新。
在SQL Server中可以這樣處理:
if not exists (select 1 from t where id = 1)
insert into t(id, update_time) values(1, getdate())
else
update t set update_time = getdate() where id = 1
那麼 MySQL 中如何?這樣的邏輯呢?MySQL 中有更簡單的方法: replace into
replace into t(id, update_time) values(1, now());
或
replace into t(id, update_time) select 1, now();
replace into 跟 insert 功能類似,不同點在於:replace into 首先嘗試插入資料到表中, 1. 如果發現表中已經有此行資料(根據主鍵或者唯一索引判斷)則先刪除此行資料,然後插入新的資料。 2. 否則,直接插入新資料。
要注意的是:插入資料的表必須有主鍵或者是唯一索引!否則的話,replace into 會直接插入資料,這將導致表中出現重複的資料。
MySQL replace into 有三種形式:
1. replace into tbl_name(col_name, ...) values(...)
2. replace into tbl_name(col_name, ...) select ...
3. replace into tbl_name set col_name=value, ...
第一種形式類似於insert into的用法,
第二種replace select的用法也類似於insert select,這種用法並不一定要求列名匹配,事實上,MYSQL甚至不關心select返回的列名,它需要的是列的位置。例如,replace into tb1( name, title, mood) select rname, rtitle, rmood from tb2; 這個例子使用replace into從 tb2中將所有資料匯入tb1中。
第三種replace set用法類似於update set用法,使用一個例如“SET col_name = col_name + 1”的賦值,則對位於右側的列名稱的引用會被作為DEFAULT(col_name)處理。因此,該賦值相當於SET col_name = DEFAULT(col_name) + 1。
前兩種形式用的多些。其中 “into” 關鍵字可以省略,不過最好加上 “into”,這樣意思更加直觀。另外,對於那些沒有給予值的列,MySQL 將自動為這些列賦上預設值。
MYSQL中replace into的用法