LAST_INSERT_ID()

文章来自: http://www.cnblogs.com/JohnABC/p/3727068.html

第一、查询和插入所使用的Connection对象必须是同一个才可以,否则返回值是不可预料的。

使 用这函数向一个给定Connection对象返回的值是该Connection对象产生对影响AUTO_INCREMENT列的最新语句第一个 AUTO_INCREMENT值的。这个值不能被其它Connection对象的影响,即它们产生它们自己的AUTO_INCREMENT值。

第二、LAST_INSERT_ID 是与table无关的,如果向表a插入数据后,再向表b插入数据,LAST_INSERT_ID返回表b中的Id值。

第三、 假如你使用一条INSERT语句插入多个行,  LAST_INSERT_ID() 只返回插入的第一行数据时产生的值。其原因是这使依靠其它服务器复制同样的 INSERT语句变得简单。

下面做个简单测试:
session 1:


"root@localhost Thu Nov  3 03:18:51 2016 03:18:51 [test]>CREATE TABLE t (
    ->     id INT AUTO_INCREMENT NOT NULL PRIMARY KEY,
    ->     name VARCHAR(10) NOT NULL
    ->   );
Query OK, 0 rows affected (0.09 sec)

"root@localhost Thu Nov  3 03:18:53 2016 03:18:53 [test]>select last_insert_id();
+------------------+
| last_insert_id() |
+------------------+
|                0 |
+------------------+
1 row in set (0.00 sec)

"root@localhost Thu Nov  3 03:19:14 2016 03:19:14 [test]>INSERT INTO t VALUES (NULL, 'Bob');
Query OK, 1 row affected (0.00 sec)

"root@localhost Thu Nov  3 03:19:30 2016 03:19:30 [test]>select last_insert_id();
+------------------+
| last_insert_id() |
+------------------+
|                1 |
+------------------+
1 row in set (0.00 sec)

"root@localhost Thu Nov  3 03:19:35 2016 03:19:35 [test]>select max(id) from t;
+---------+
| max(id) |
+---------+
|       1 |
+---------+
1 row in set (0.00 sec)

session 2:

在session2 中向表中再插入一行,查看 last_insert_id () 的值为 2.

"root@localhost Thu Nov  3 03:19:54 2016 03:19:54 [test]>INSERT INTO t VALUES (NULL, 'Bob');
Query OK, 1 row affected (0.01 sec)

"root@localhost Thu Nov  3 03:20:03 2016 03:20:03 [test]>select last_insert_id();
+------------------+
| last_insert_id() |
+------------------+
|                2 |
+------------------+
1 row in set (0.00 sec)

session 1:

再回到session 1 ,查看 last_insert_id () 的值还是 1 。

"root@localhost Thu Nov  3 03:19:39 2016 03:19:39 [test]>select last_insert_id();
+------------------+
| last_insert_id() |
+------------------+
|                1 |
+------------------+
1 row in set (0.00 sec)


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值