這篇文章主要介紹了MySQL中replace into語句的用法詳解,本文講解了replace into語句的多種寫法,replace into語句的作用等內(nèi)容,需要的朋友可以參考下
在向表中插入數(shù)據(jù)的時(shí)候,經(jīng)常遇到這樣的情況:
1、首先判斷數(shù)據(jù)是否存在;
2、如果不存在,則插入;
3、如果存在,則更新。
在 SQL Server 中可以這樣寫:
復(fù)制代碼代碼如下:
if not exists (select 1 from table where id = 1) insert into table(id, update_time) values(1, getdate()) else update table set update_time = getdate() where id = 1
在MySQL 中也可以先select,判斷是否存在,存在則 update 否則 insert
但在MySQL 中有更簡單的方法,使用 replace into關(guān)鍵字
復(fù)制代碼代碼如下:
replace into table(id, update_time) values(1, now());
或
復(fù)制代碼代碼如下:
replace into table(id, update_time) select 1, now();
replace into 跟 insert 功能類似,不同點(diǎn)在于:replace into 首先嘗試插入數(shù)據(jù)到表中。
1、如果發(fā)現(xiàn)表中已經(jīng)有此行數(shù)據(jù)(根據(jù)主鍵或者唯一索引判斷)則先刪除此行數(shù)據(jù),然后插入新的數(shù)據(jù)。
2、 否則,直接插入新數(shù)據(jù)。
要注意的是:插入數(shù)據(jù)的表必須有主鍵或者是唯一索引!否則的話,replace into 會(huì)直接插入數(shù)據(jù),這將導(dǎo)致表中出現(xiàn)重復(fù)的數(shù)據(jù)。
MySQL中replace into有三種寫法:
復(fù)制代碼代碼如下:
1. replace into table(col, ...) values(...)
2. replace into table(col, ...) select ...
3. replace into table set col=value, ...
前兩種形式用的多些。其中 “into” 關(guān)鍵字可以省略,不過最好加上 “into”,這樣意思更加直觀。
另外,對(duì)于那些沒有給予值的列,MySQL 將自動(dòng)為這些列賦上默認(rèn)值。
可惜的是replace不支持update某些特性,也就不能直接當(dāng)作update使用:
常見update寫法:update table set col=col+1 where id=1;
使用replace into不支持這樣的寫法:replace into table set col=col+1,id=1;
1、首先判斷數(shù)據(jù)是否存在;(沒問題)
2、如果不存在,則插入;(沒問題)
3、如果存在,某字段值在原來的基礎(chǔ)上加上或減去某個(gè)數(shù),如加一操作。(不支持)