mysql insert into, insert ignore into, insert into on duplicate key update

几个sql的执行情况汇总如下表:

指令已存在不存在
insert报错插入
insert ignore忽略插入
insert into on duplicate key update更新插入
insert ignore into on duplicate key update更新插入

数据表要求有主键或唯一键。

另外,以上操作,都会使自增字段自增。

下面做下具体的测试。

建表

CREATE TABLE `test5` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(45) NOT NULL,
  `age` tinyint(4) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`),
  UNIQUE KEY `name_UNIQUE` (`name`)
) ENGINE=InnoDB;

id是主键,自增,name是唯一键。

insert into

> insert into test5 (name, age) values('John', 1);
Query OK, 1 row affected (0.00 sec)

查询

mysql> select * from test5;
+----+------+-----+
| id | name | age |
+----+------+-----+
|  1 | John |   1 |
+----+------+-----+
1 row in set (0.00 sec)

已插入新记录。

再次插入

mysql> insert into test5 (name, age) values('John', 1);
ERROR 1062 (23000): Duplicate entry 'John' for key 'name_UNIQUE'

报错,唯一键冲突。

insert ignore into

mysql> insert ignore into test5 (name, age) values('John', 1);
Query OK, 0 rows affected, 1 warning (0.00 sec)

查询

mysql> select * from test5;
+----+------+-----+
| id | name | age |
+----+------+-----+
|  1 | John |   1 |
+----+------+-----+
1 row in set (0.00 sec)

ignore 会忽略错误。

insert into on duplicate update

mysql> insert into test5 (name, age) values('John', 2) on duplicate key update age=2;
Query OK, 2 rows affected (0.00 sec)

查询

mysql> select * from test5;
+----+------+-----+
| id | name | age |
+----+------+-----+
|  1 | John |   2 |
+----+------+-----+
1 row in set (0.00 sec)

age更新为2。

不存在记录时

mysql> insert into test5 (name, age) values('Alex', 2) on duplicate key update age=2;
Query OK, 1 row affected (0.00 sec)

查询

mysql> select * from test5;
+----+------+-----+
| id | name | age |
+----+------+-----+
|  1 | John |   2 |
|  7 | Alex |   2 |
+----+------+-----+
2 rows in set (0.00 sec)

会插入新记录。

insert ignore into on duplicate update

mysql> insert ignore into test5 (name, age) values('John', 3) on duplicate key update age=3;
Query OK, 2 rows affected (0.01 sec)

查询

mysql> select * from test5;
+----+------+-----+
| id | name | age |
+----+------+-----+
|  1 | John |   3 |
|  7 | Alex |   2 |
+----+------+-----+
2 row in set (0.00 sec)

John的age更新为3。

不存在记录时

mysql> insert ignore into test5 (name, age) values('Bob', 3) on duplicate key update age=3;
Query OK, 1 row affected (0.00 sec)

mysql> select * from test5;
+----+------+-----+
| id | name | age |
+----+------+-----+
|  1 | John |   3 |
|  7 | Alex |   2 |
|  8 | Bob  |   3 |
+----+------+-----+
3 rows in set (0.00 sec)

会插入新记录。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值