mysql into_MYSQL中replace into的用法
新建一個(gè)test表,三個(gè)字段,id,title,uid,? id是自增的主鍵,uid是唯一索引;
插入兩條數(shù)據(jù)
insert into test(title,uid) VALUES ('123465','1001');insert into test(title,uid) VALUES ('123465','1002');
執(zhí)行單條插入數(shù)據(jù)可以看到,執(zhí)行結(jié)果如下:
[SQL]insert into test(title,uid) VALUES ('123465','1001');
受影響的行: 1時(shí)間: 0.175s
使用 replace into插入數(shù)據(jù)時(shí):
REPLACE INTO test(title,uid) VALUES ('1234657','1003');
執(zhí)行結(jié)果:
[SQL]REPLACE INTO test(title,uid) VALUES ('1234657','1003');
受影響的行: 1
時(shí)間: 0.035s
當(dāng)前數(shù)據(jù)庫(kù)test表所有數(shù)據(jù)如下:
當(dāng)uid存在時(shí),使用replace into 語(yǔ)句
REPLACE INTO test(title,uid) VALUES ('1234657','1001');[SQL]REPLACE INTO test(title,uid) VALUES ('1234657','1001');
受影響的行:2時(shí)間:0.140s
replace into t(id, update_time) values(1, now());
或
replace into t(id, update_time) select 1, now();
replace into 跟 insert 功能類(lèi)似,不同點(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, ...
第一種形式類(lèi)似于insert into的用法,
第二種replace select的用法也類(lèi)似于insert select,這種用法并不一定要求列名匹配,事實(shí)上,MYSQL甚至不關(guān)心select返回的列名,它需要的是列的位置。例如,replace into tb1( name, title, mood) select rname, rtitle, rmood from tb2;?這個(gè)例子使用replace into從?tb2中將所有數(shù)據(jù)導(dǎo)入tb1中。
第三種replace set用法類(lèi)似于update set用法,使用一個(gè)例如“SET col_name = col_name + 1”的賦值,則對(duì)位于右側(cè)的列名稱(chēng)的引用會(huì)被作為DEFAULT(col_name)處理。因此,該賦值相當(dāng)于SET col_name = DEFAULT(col_name) + 1。
前兩種形式用的多些。其中 “into” 關(guān)鍵字可以省略,不過(guò)最好加上 “into”,這樣意思更加直觀。另外,對(duì)于那些沒(méi)有給予值的列,MySQL 將自動(dòng)為這些列賦上默認(rèn)值。
總結(jié)
以上是生活随笔為你收集整理的mysql into_MYSQL中replace into的用法的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 超级马里奥游戏像素素材_《超级马里奥3D
- 下一篇: linux cmake编译源码,linu