mysql中insert ignore、insert和replace的区别及说明

这篇文章主要介绍了mysql中insert ignore、insert和replace的区别及说明,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

insert ignore、insert和replace的区别

指令已存在不存在举例
insert报错插入insert into names(name, age) values(“小明”, 23);
insert ignore忽略插入insert ignore into names(name, age) values(“小明”, 24);
replace替换插入replace into names(name, age) values(“小明”, 25);

表要求:有PrimaryKey,或者unique索引

结果:表id都会自增

测试代码

创建表

CREATE TABLE names(     id INT(10) PRIMARY KEY AUTO_INCREMENT,     name VARCHAR(255) UNIQUE,     age INT(10) )

插入数据

mysql> insert into names(name, age) values("小明", 24); mysql> insert into names(name, age) values("大红", 24); mysql> insert into names(name, age) values("大壮", 24); mysql> insert into names(name, age) values("秀英", 24); mysql> select * from names; +----+--------+------+ | id | name   | age  | +----+--------+------+ |  1 | 小明   |   24 | |  2 | 大红   |   24 | |  3 | 大壮   |   24 | |  4 | 秀英   |   24 | +----+--------+------+

insert

插入已存在, id会自增,但是插入不成功,会报错

mysql> insert into names(name, age) values("小明", 23); ERROR 1062 (23000): Duplicate entry '小明' for key 'name'

replace

已存在替换,删除原来的记录,添加新的记录

mysql> replace into names(name, age) values("小明", 23); Query OK, 2 rows affected (0.00 sec) mysql> select * from names; +----+--------+------+ | id | name   | age  | +----+--------+------+ |  2 | 大红   |   24 | |  3 | 大壮   |   24 | |  4 | 秀英   |   24 | |  6 | 小明   |   23 | +----+--------+------+

不存在替换,添加新的记录

mysql> replace into names(name, age) values("大名", 23); Query OK, 1 row affected (0.00 sec) mysql> select * from names; +----+--------+------+ | id | name   | age  | +----+--------+------+ |  2 | 大红   |   24 | |  3 | 大壮   |   24 | |  4 | 秀英   |   24 | |  6 | 小明   |   23 | |  7 | 大名   |   23 | +----+--------+------+

insert ignore

插入已存在,忽略新插入的记录,id会自增,不会报错

mysql> insert ignore into names(name, age) values("大壮", 25); Query OK, 0 rows affected, 1 warning (0.00 sec)

插入不存在,添加新的记录 

mysql> insert ignore into names(name, age) values("壮壮", 25); Query OK, 1 row affected (0.01 sec) mysql> select * from  names; +----+--------+------+ | id | name   | age  | +----+--------+------+ |  2 | 大红   |   24 | |  3 | 大壮   |   24 | |  4 | 秀英   |   24 | |  6 | 小明   |   23 | |  7 | 大名   |   23 | | 10 | 壮壮   |   25 | +----+--------+------+

以上为个人经验,希望能给大家一个参考,也希望大家多多支持0133技术站。 

以上就是mysql中insert ignore、insert和replace的区别及说明的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » 数据库