MySQL 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, ...
前兩種形式用的多些。其中 “into” 關鍵字可以省略,不過最好加上 “into”,這樣意思更加直觀。另外,對於那些沒有給予值的列,MySQL 將自動爲這些列賦上默認值。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章