一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

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

时间:2013-11-20 编辑:简简单单 来源:一聚教程网


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

insert into表示插入数据,数据库会检查主键,如果出现重复会报错;
replace into表示插入替换数据,需求表中有PrimaryKey,或者unique索引,如果数据库已经存在数据,则用新数据替换,如果没有数据效果则和insert into一样;
insert ignore表示,如果中已经存在相同的记录,则忽略当前新数据;

下面通过代码说明之间的区别,如下:

create table testtb(
id int not null primary key,
name varchar(50),
age int
);

insert into testtb(id,name,age)values(1,"bb",13);
select * from testtb;
insert ignore into testtb(id,name,age)values(1,"aa",13);
select * from testtb;//仍是1,“bb”,13,因为id是主键,出现主键重复但使用了ignore则错误被忽略
replace into testtb(id,name,age)values(1,"aa",12);
select * from testtb; //数据变为1,"aa",12

 

举例说明

 

insert into

 

table 1

 

id name

 

1    tb

 

2    zp

 

table2

 

id(主键) name

 

1    tb

 

2    cw

 

3    zp

 

insert ignore into table1 select  * from table2执行结果为

 

table1

 

id name

 

1    tb

 

2    zp

 

3    zp

 

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

 

replace into

 

table 1

 

id name    ps

 

1    tb    a

 

2    zp    b

 

table2

 

id(主键) name

 

1    tb

 

2    cw

 

3    zp

 

replace into table1 select  * from table2执行结果为

 

table1

 

id name  ps

 

1    tb      NULL

 

2    cw     NULL

 

3    zp     NULL

 

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

总结

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

热门栏目