遇到一个小伙伴说,为什么last_insert_id()得到的结果与预期的不一样呢,于是,我认真的去研究的一下这个参数,研究结果请点击全文。 首先,举个栗子wing@3306>show create table tt; +-------+-----------------------------------------------------------------------------------------------------------------------+ | Table | Create Table | +-------+-----------------------------------------------------------------------------------------------------------------------+ | tt | CREATE TABLE `tt` ( `id` int(11) NOT NULL AUTO_INCREMENT, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 | +-------+-----------------------------------------------------------------------------------------------------------------------+ 1 row in set (0.00 sec) # 没有指定值的时候,last_insert_id()符合预期希望 wing@3306>insert into tt values(); Query OK, 1 row affected (0.00 sec) wing@3306>select last_insert_id(); +------------------+ | last_insert_id() | +------------------+ | 1 | +------------------+ 1 row in set (0.00 sec) wing@3306>insert into tt values(); Query OK, 1 row affected (0.00 sec) wing@3306>select last_insert_id(); +------------------+ | last_insert_id() | +------------------+ | 2 | +------------------+ 1 row in set (0.00 sec) # what?不是应该是5么,为什么是第一个插入的值3?last_insert_id开始有一点不符合预期了。。 wing@3306>insert into tt values(),(),(); Query OK, 3 rows affected (0.01 sec) Records: 3 Duplicates: 0 Warnings: 0 wing@3306>select last_insert_id(); +------------------+ | last_insert_id() | +------------------+ | 3 | +------------------+ 1 row in set (0.00 sec) wing@3306>insert into tt values(),(),(); Query OK, 3 rows affected (0.01 sec) Records: 3 Duplicates: 0 Warnings: 0 wing@3306>select last_insert_id(); +------------------+ | last_insert_id() | +------------------+ | 6 | +------------------+ 1 row in set (0.00 sec) # 纳尼?按照预期不是10么?为什么还是之前的6?last_insert_id()我不懂你啊。。 wing@3306>insert into tt values(10); Query OK, 1 row affected (0.01 sec) wing@3306>select last_insert_id(); +------------------+ | last_insert_id() | +------------------+ | 6 | +------------------+ 1 row in set (0.00 sec) 其次,研究一下查阅MySQL官方文档,真的太重要了。。。 官方出处: http://dev.mysql.com/doc/refman/5.6/en/information-functions.html#function_last-insert-id
然后,剖析一下请认真阅读上述翻译中的黑色字体,牢记last_insert_id()的约束。
最后,总结一下记住last_insert_id()的约束。。 最近一次INSERT语句在autpincrement列上自动生成的第一个值。 (责任编辑:最模板) |