MySQL中replace into語句的用法詳解
在向表中插入數(shù)據(jù)的時候,經(jīng)常遇到這樣的情況:
1、首先判斷數(shù)據(jù)是否存在;
2、如果不存在,則插入;
3、如果存在,則更新。
在 SQL Server 中可以這樣寫:
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)鍵字
或
replace into table(id, update_time) select 1, now();
replace into 跟 insert 功能類似,不同點在于:replace into 首先嘗試插入數(shù)據(jù)到表中。
1、如果發(fā)現(xiàn)表中已經(jīng)有此行數(shù)據(jù)(根據(jù)主鍵或者唯一索引判斷)則先刪除此行數(shù)據(jù),然后插入新的數(shù)據(jù)。
2、 否則,直接插入新數(shù)據(jù)。
要注意的是:插入數(shù)據(jù)的表必須有主鍵或者是唯一索引!否則的話,replace into 會直接插入數(shù)據(jù),這將導(dǎo)致表中出現(xiàn)重復(fù)的數(shù)據(jù)。
MySQL中replace into有三種寫法:
1. replace into table(col, ...) values(...)
2. replace into table(col, ...) select ...
3. replace into table set col=value, ...
前兩種形式用的多些。其中 “into” 關(guān)鍵字可以省略,不過最好加上 “into”,這樣意思更加直觀。
另外,對于那些沒有給予值的列,MySQL 將自動為這些列賦上默認值。
可惜的是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ǔ)上加上或減去某個數(shù),如加一操作。(不支持)
- MySQL into_Mysql中replace與replace into用法案例詳解
- 細說mysql replace into用法
- mysql 中 replace into 與 insert into on duplicate key update 的用法和不同點實例分析
- Mysql中replace與replace into的用法講解
- mysql 的replace into實例詳解
- 淺析MySQL replace into 的用法
- MySQL中REPLACE INTO和INSERT INTO的區(qū)別分析
- MySQL Replace INTO的使用
- MySQL中replace into與replace區(qū)別詳解
相關(guān)文章
系統(tǒng)高吞吐量下的數(shù)據(jù)庫重復(fù)寫入問題分析解決
這篇文章主要介紹了系統(tǒng)高吞吐量下的數(shù)據(jù)庫重復(fù)寫入問題分析解決,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-04-04MySQL數(shù)據(jù)庫常用操作技巧總結(jié)
這篇文章主要介紹了MySQL數(shù)據(jù)庫常用操作技巧,結(jié)合實例形式總結(jié)分析了mysql查詢、存儲過程、字符串截取、時間、排序等常用操作技巧,需要的朋友可以參考下2018-03-03MySQL數(shù)據(jù)庫中varchar類型的數(shù)字比較大小的方法
varchar類型的數(shù)據(jù)是不能直接比較大小的,那么MySQL數(shù)據(jù)庫中varchar類型如何進行數(shù)字比較大小的,本文就詳細的介紹一下2021-11-11MySQL關(guān)于ERROR 1290 (HY000)報錯解決方法
在本篇文章里小編給大家整理的是關(guān)于MySQL關(guān)于ERROR 1290 (HY000)報錯的解決方法,有興趣的朋友們可以參考下。2019-09-09