插入失败时

[root@yejr.me]> CREATE TABLE `t` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`c1` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB;

# 第一次插入,没问题
[root@yejr.me]> insert into t select 0,rand()*1024;
[root@yejr.me]> select last_insert_id();
+------------------+
| last_insert_id() |
+------------------+
| 1 |
+------------------+

# 第二次插入,也没问题
[root@yejr.me]> insert into t select 0,rand()*1024;
[root@yejr.me]> select last_insert_id();
+------------------+
| last_insert_id() |
+------------------+
| 2 |
+------------------+

# 第三次插入,故意制造一个重复主键,这次就不对了
[root@yejr.me]> insert into t values(0,rand()*1024), (3, rand()*1024);
ERROR 1062 (23000): Duplicate entry '3' for key 'PRIMARY'
[root@yejr.me]> select last_insert_id(http://www.amjmh.com/v/BIBRGZ_558768/);
+------------------+
| last_insert_id() |
+------------------+
| 3 |
+------------------+

# 表中实际只有两条记录
[root@yejr.me]> select * from t;
+----+-----+
| id | c1 |
+----+-----+
| 1 | 784 |
| 2 | 574 |
+----+-----+
2 rows in set (0.00 sec)

原文地址:https://www.cnblogs.com/ly570/p/11448343.html