MySQL last_insert_id的值

user_id设置为primary key,auto_increment

查询现有user_id

mysql> select * from test;
+---------+----------+
| user_id | name     |
+---------+----------+
|       1 | aaaaaa   |
|       2 | bbbbbbbb |
+---------+----------+
2 rows in set (0.03 sec)

插入一条记录

mysql> insert into test (name) values ('ccccc');
Query OK, 1 row affected (0.01 sec)

查询last_insert_id

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

一次插入多条记录

mysql> insert into test (name) values ('ccccc'),('dddddd'),('ee');
Query OK, 3 rows affected (0.04 sec)
Records: 3  Duplicates: 0  Warnings: 0

再次查询last_insert_id

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

对比整个表

mysql> select * from test;
+---------+----------+
| user_id | name     |
+---------+----------+
|       1 | aaaaaa   |
|       2 | bbbbbbbb |
|       3 | ccccc    |
|       4 | ccccc    |
|       5 | dddddd   |
|       6 | ee       |
+---------+----------+
6 rows in set (0.00 sec)

发现last_insert_id只是返回最后一次插入的第一条的primary key,并不是返回最后一次插入的最大的primary key

 

如果insert 避免重复使用了on duplicate key update,这个时候使用select last_insert_id();不会返回更新的id,需要在update中加点小动作

mysql> insert into test (user_id,name) values (2,'aaa') on duplicate key update name='duplicate name', user_id=last_insert_id(user_id);
Query OK, 2 rows affected (0.02 sec)

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

mysql> insert into test (name) values ('aaa');
Query OK, 1 row affected (0.00 sec)

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

注意primary key一定要有auto_increment属性,不然last_insert_id()会返回0,

如果primary key没有auto_increment属性,就先drop primary key,然后再change column加上primary key和auto_increment属性,添加primary key的时候注意id不能为0,也不能有重复的
 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值