<p><strong>新建一個(gè)test表攒巍,三個(gè)字段而柑,id竹勉,title在刺,uid,? id是自增的主鍵贷岸,uid是唯一索引跃闹;</strong></p><p>插入兩條數(shù)據(jù)</p><p/><pre>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</pre><p/><p>使用 replace into插入數(shù)據(jù)時(shí):</p><pre>REPLACE?INTO?test(title,uid)?VALUES?('1234657','1003');
執(zhí)行結(jié)果:[SQL]REPLACE?INTO?test(title,uid)?VALUES?('1234657','1003');
受影響的行:?1時(shí)間:?0.035s</pre><p>當(dāng)前數(shù)據(jù)庫test表所有數(shù)據(jù)如下:</p><p class="image-package"><img class="uploaded-img" src="https://upload-images.jianshu.io/upload_images/9645324-435ffba3f21054af.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" width="auto" height="auto"/></p><p class="image-package">當(dāng)uid存在時(shí),使用replace into 語句</p><pre>REPLACE?INTO?test(title,uid)?VALUES?('1234657','1001');[SQL]REPLACE?INTO?test(title,uid)?VALUES?('1234657','1001');
受影響的行:?2時(shí)間:?0.140s</pre><p class="image-package"><img class="uploaded-img" src="https://upload-images.jianshu.io/upload_images/9645324-a9e2d868884d6e63.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" width="auto" height="auto"/></p><p class="image-package">replace into t(id, update_time) values(1, now());</p><p>或</p><p>replace into t(id, update_time) select 1, now();</p><p>replace into 跟 insert 功能類似辣卒,不同點(diǎn)在于:replace into 首先嘗試插入數(shù)據(jù)到表中掷贾,<strong>?1. 如果發(fā)現(xiàn)表中已經(jīng)有此行數(shù)據(jù)(根據(jù)主鍵或者唯一索引判斷)則先刪除此行數(shù)據(jù),然后插入新的數(shù)據(jù)荣茫。 2. 否則想帅,直接插入新數(shù)據(jù)。</strong></p><p>要注意的是:插入數(shù)據(jù)的表必須有主鍵或者是唯一索引啡莉!否則的話港准,replace into 會(huì)直接插入數(shù)據(jù),這將導(dǎo)致表中出現(xiàn)重復(fù)的數(shù)據(jù)咧欣。</p><p>MySQL replace into 有三種形式:</p><p>1. replace into tbl_name(col_name, ...) values(...)</p><p>2. replace into tbl_name(col_name, ...) select ...</p><p>3. replace into tbl_name set col_name=value, ...</p><p>第一種形式類似于insert into的用法浅缸,</p><p>第二種replace select的用法也類似于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中。</p><p>第三種replace set用法類似于update set用法喝滞,使用一個(gè)例如“SET col_name = col_name + 1”的賦值阁将,則對(duì)位于右側(cè)的列名稱的引用會(huì)被作為DEFAULT(col_name)處理。因此右遭,該賦值相當(dāng)于SET col_name = DEFAULT(col_name) + 1做盅。</p><p>前兩種形式用的多些缤削。其中 “into” 關(guān)鍵字可以省略,不過最好加上 “into”吹榴,這樣意思更加直觀僻他。另外,對(duì)于那些沒有給予值的列腊尚,MySQL 將自動(dòng)為這些列賦上默認(rèn)值吨拗。</p><p>轉(zhuǎn):“<a>http://www.cnblogs.com/c-961900940/p/6197878.html</a>”</p>