国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 數(shù)據(jù)庫 > MySQL > 正文

mysql中INSERT IGNORE 與INSERT INTO,REPLACE INTO的區(qū)別

2024-07-24 12:37:03
字體:
供稿:網(wǎng)友

在mysql中INSERT IGNORE,INSERT INTO,REPLACE INTO三者都是插入數(shù)據(jù)到mysql數(shù)據(jù)庫的語句,那么這三者之間到底有什么區(qū)別呢?

mysql中常用的三種插入數(shù)據(jù)的語句:

insert into表示插入數(shù)據(jù),數(shù)據(jù)庫會檢查主鍵,如果出現(xiàn)重復會報錯;

replace into表示插入替換數(shù)據(jù),需求表中有PrimaryKey,或者unique索引,如果數(shù)據(jù)庫已經(jīng)存在數(shù)據(jù),則用新數(shù)據(jù)替換,如果沒有數(shù)據(jù)效果則和insert into一樣;

insert ignore表示,如果中已經(jīng)存在相同的記錄,則忽略當前新數(shù)據(jù);下面通過代碼說明之間的區(qū)別,如下:

  1. create table testtb(  
  2. id int not null primary key,  
  3. name varchar(50),  
  4. age int  
  5. ); 
  6. insert into testtb(id,name,age)values(1,"bb",13);  
  7. select * from testtb;  
  8. insert ignore into testtb(id,name,age)values(1,"aa",13);  
  9. select * from testtb;//仍是1,“bb”,13,因為id是主鍵,出現(xiàn)主鍵重復但使用了ignore則錯誤被忽略  
  10. replace into testtb(id,name,age)values(1,"aa",12);  
  11. select * from testtb; //數(shù)據(jù)變?yōu)?,"aa",12 

舉例說明,代碼如下:

  1. insert into 
  2.  
  3. table 1 
  4.  
  5. id name 
  6.  
  7. 1    tb 
  8.  
  9. 2    zp 
  10.  
  11. table2 
  12.  
  13. id(主鍵) name 
  14.  
  15. 1    tb 
  16.  
  17. 2    cw 
  18.  
  19. 3    zp 
  20.  
  21. insert ignore into table1 select  * from table2執(zhí)行結(jié)果為 
  22.  
  23. table1 
  24.  
  25. id name 
  26.  
  27. 1    tb 
  28.  
  29. 2    zp 
  30.  
  31. 3    zp 

注:如果使用的是insert into 發(fā)現(xiàn)重復的會報錯,而insert ignore  into 發(fā)現(xiàn)將要插入的數(shù)據(jù)行中包含唯一索引的字段值已存在,會丟棄掉這行數(shù)據(jù),不做任何處理.

  1. replace into 
  2.  
  3. table 1 
  4.  
  5. id name    ps 
  6.  
  7. 1    tb    a 
  8.  
  9. 2    zp    b 
  10.  
  11. table2 
  12.  
  13. id(主鍵) name 
  14.  
  15. 1    tb 
  16.  
  17. 2    cw 
  18.  
  19. 3    zp 
  20.  
  21. replace into table1 select  * from table2執(zhí)行結(jié)果為 
  22.  
  23. table1   //Vevb.com
  24.  
  25. id name  ps 
  26.  
  27. 1    tb      NULL 
  28.  
  29. 2    cw     NULL 
  30.  
  31. 3    zp     NULL 

注:REPLACE發(fā)現(xiàn)重復的先刪除再插入,如果記錄有多個字段,在插入的時候如果有的字段沒有賦值,那么新插入的記錄這些字段為空.

總結(jié):NSERT IGNORE 與INSERT INTO的區(qū)別就是INSERT IGNORE會忽略數(shù)據(jù)庫中已經(jīng)存在 的數(shù)據(jù),如果數(shù)據(jù)庫沒有數(shù)據(jù),就插入新的數(shù)據(jù),如果有數(shù)據(jù)的話就跳過這條數(shù)據(jù),這樣就可以保留數(shù)據(jù)庫中已經(jīng)存在數(shù)據(jù),達到在間隙中插入數(shù)據(jù)的目的.

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 科尔| 祁连县| 扎赉特旗| 泸州市| 河南省| 合水县| 太和县| 二连浩特市| 佛冈县| 义马市| 台南市| 鄂托克旗| 买车| 任丘市| 临汾市| 静海县| 精河县| 盐亭县| 永丰县| 天峻县| 桂阳县| 壶关县| 象州县| 通渭县| 积石山| 涡阳县| 博白县| 定结县| 巨鹿县| 遂溪县| 琼海市| 濮阳县| 洪江市| 安徽省| 临清市| 河津市| 望城县| 周至县| 松桃| 乌拉特前旗| 深水埗区|