MySQL:討人喜歡的 MySQL replace into 用法(insert into 的加強版)

討人喜歡的 MySQL replace into 用法(insert into 的加強版)

在向表中插入數據的時候,常常遇到這樣的狀況:1. 首先判斷數據是否存在; 2. 若是不存在,則插入;3.若是存在,則更新。mysql

在 SQL Server 中能夠這樣處理:sql

   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 intopost

replace into t(id, update_time) values(1, now());

.net

replace into t(id, update_time) select 1, now();

replace into 跟 insert 功能相似,不一樣點在於:replace into 首先嚐試插入數據到表中, 1. 若是發現表中已經有此行數據(根據主鍵或者惟一索引判斷)則先刪除此行數據,而後插入新的數據。 2. 不然,直接插入新數據。code

要注意的是:插入數據的表必須有主鍵或者是惟一索引!不然的話,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 將自動爲這些列賦上默認值。get

相關文章
相關標籤/搜索