A-A+

INSERT IGNORE 与 INSERT INTO的区别

2017年10月18日 编程技术 暂无评论

INSERT IGNORE 与INSERT INTO的区别就是INSERT IGNORE会忽略数据库中已经存在的数据,如果数据库没有数据,就插入新的数据,如果有数据的话就跳过这条数据.

例,insert ignore表示,如果中已经存在相同的记录,则忽略当前新数据;

insert ignore into table(name) select name from table2

例,INSERT INTO有无数据都插入,如果主键则不插入.

1.insert语句一次可以插入多组值,每组值用一对圆括号括起来,用逗号分隔,如下:

insert into `news`(title,body,time) values('www.xiaohuboke.com','body 1',now()),('title 2','body 2',now());

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

  1. create table testtb(    
  2. id int not null primary key,    
  3. name varchar(50),    
  4. age int    
  5. );   
  6.    
  7. insert into testtb(id,name,age)values(1,"www.xiaohuboke.com",13);    
  8. select * from testtb;    
  9. insert ignore into testtb(id,name,age)values(1,"aa",13);    
  10. select * from testtb;//仍是1,“bb”,13,因为id是主键,出现主键重复但使用了ignore则错误被忽略    
  11. replace into testtb(id,name,age)values(1,"aa",12);    
  12. select * from testtb; //数据变为1,"aa",12  
标签:

给我留言