replace into
生活随笔
收集整理的這篇文章主要介紹了
replace into
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
討人喜歡的 MySQL replace into 用法(insert into 的增強(qiáng)版)
在向表中插入數(shù)據(jù)的時(shí)候,經(jīng)常遇到這樣的情況:1. 首先判斷數(shù)據(jù)是否存在; 2. 如果不存在,則插入;3.如果存在,則更新。
在 SQL Server 中可以這樣處理:
if not exists (select 1 from t where id = 1)insert into t(id, update_time) values(1, getdate())elseupdate t set update_time = getdate() where id = 1那么 MySQL 中如何實(shí)現(xiàn)這樣的邏輯呢?別著急!MySQL 中有更簡單的方法: replace into
replace into t(id, update_time) values(1, now());或
replace into t(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 有三種形式:
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” 關(guān)鍵字可以省略,不過最好加上 “into”,這樣意思更加直觀。另外,對于那些沒有給予值的列,MySQL 將自動(dòng)為這些列賦上默認(rèn)值。
總結(jié)
以上是生活随笔為你收集整理的replace into的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 百度新key申请步骤
- 下一篇: 路由器简介与IOS介绍