获取最后一个插入 ID 显示错误的数字 [英] Fetching last insert id shows wrong number

查看:59
本文介绍了获取最后一个插入 ID 显示错误的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一张包含三条记录的表格.有一个归档为 auto_increment.ID 是 1、2、3...

I have table with three records. There is one filed as auto_increment. The ID's are 1, 2, 3...

当我运行查询时

SELECT LAST_INSERT_ID() FROM myTable

结果是5,最后一个ID也是3.为什么?

The result is 5, even the last ID is 3. Why?

什么更好用?LAST_INSERT_ID() 还是 SELECT MAX(ID) FROM myTable?

And what is better to use? LAST_INSERT_ID() or SELECT MAX(ID) FROM myTable?

推荐答案

last_insert_id() 与特定表无关.在同一个连接中,所有表共享相同.

last_insert_id() has no relation to specific tables. In the same connection, all table share the same.

下面是它的演示.

mysql> create table t1(c1 int primary key auto_increment);
Query OK, 0 rows affected (0.11 sec)

mysql> create table t2(c1 int primary key auto_increment);
Query OK, 0 rows affected (0.06 sec)

mysql> insert into t1 values(null);
Query OK, 1 row affected (0.01 sec)

mysql> insert into t2 values(4);
Query OK, 1 row affected (0.00 sec)

mysql> insert into t2 values(null);
Query OK, 1 row affected (0.02 sec)

mysql> select last_insert_id() from t1;
+------------------+
| last_insert_id() |
+------------------+
|                5 |
+------------------+
1 row in set (0.00 sec)

这篇关于获取最后一个插入 ID 显示错误的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆