A-A+

mysql中INSERT IGNORE 与INSERT INTO,REPLACE INTO的区别

2017年10月25日 PHP技术文章 暂无评论 阅读 0 views 次

在mysql中INSERT IGNORE,INSERT INTO,REPLACE INTO三者都是插入数据到mysql数据库的语句,那么这三者之间到底有什么区别呢?

mysql中常用的三种插入数据的语句:

insert into表示插入数据,数据库会检查主键,如果出现重复会报错;

replace into表示插入替换数据,需求表中有PrimaryKey,或者unique索引,如果数据库已经存在数据,则用新数据替换,如果没有数据效果则和insert into一样;

insert ignore表示,如果中已经存在相同的记录,则忽略当前新数据;下面通过代码说明之间的区别,如下:

  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是主键,出现主键重复但使用了ignore则错误被忽略    
  10. replace into testtb(id,name,age)values(1,"aa",12);    
  11. select * from testtb; //数据变为1,"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执行结果为   
  22.    
  23. table1   
  24.    
  25. id name   
  26.    
  27. 1    tb   
  28.    
  29. 2    zp   
  30.    
  31. 3    zp   

注:如果使用的是insert into 发现重复的会报错,而insert ignore into 发现将要插入的数据行中包含唯一索引的字段值已存在,会丢弃掉这行数据,不做任何处理.

  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执行结果为   
  22.    
  23. table1   --www.xiariboke.net  
  24.    
  25. id name  ps   
  26.    
  27. 1    tb      NULL   
  28.    
  29. 2    cw     NULL   
  30.    
  31. 3    zp     NULL   

注:REPLACE发现重复的先删除再插入,如果记录有多个字段,在插入的时候如果有的字段没有赋值,那么新插入的记录这些字段为空.

总结:NSERT IGNORE 与INSERT INTO的区别就是INSERT IGNORE会忽略数据库中已经存在 的数据,如果数据库没有数据,就插入新的数据,如果有数据的话就跳过这条数据,这样就可以保留数据库中已经存在数据,达到在间隙中插入数据的目的.

标签:

给我留言