淺析MySQL replace into 的用法_Mysql

來源:互聯網
上載者:User

在 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 有三種形式:

複製代碼 代碼如下:

 replace into tbl_name(col_name, ...) values(...)
 replace into tbl_name(col_name, ...) select ...
 replace into tbl_name set col_name=value, ...

前兩種形式用的多些。其中 “into” 關鍵字可以省略,不過最好加上 “into”,這樣意思更加直觀。另外,對於那些沒有給予值的列,MySQL 將自動為這些列賦上預設值。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.