当前位置: 移动技术网 > IT编程>数据库>Mysql > Mysql中LAST_INSERT_ID()的函数使用详解

Mysql中LAST_INSERT_ID()的函数使用详解

2017年12月12日  | 移动技术网IT编程  | 我要评论

最近和sobin在做一个精品课程的项目,因为用到一个固定的id作为表间关联,所以在前一个表插入数据后要把插入数据生成的自增id传递给下一个表。研究了一番决定使用mysql提供了一个last_insert_id()的函数。

复制代码 代码如下:

last_insert_id() (with no argument) returns the first automatically generated value that was set for an auto_increment column by the most recently executed insert or update statement to affect such a column. for example, after inserting a row that generates an auto_increment value, you can get the value like this:
mysql> select last_insert_id();
-> 195

简单说来,就是这个函数将返回插入的那条记录在表中自增的那个字段的值,一般我们都给那个自增字段命名为id。这样就可以返回刚插入的记录的id值了。

一个简单的例子:

复制代码 代码如下:

$query="insert into `testtable` (`clou1`,`clou2`) values ('testvalue','test')";
mysql_query($query);
$query="select last_insert_id()";
$result=mysql_query($query);
$rows=mysql_fetch_row($result);
echo $rows[0];

这个函数是基于connection的,也就是不会被其他客户端的connection影响到,所以结果是准确的。如果使用select max(id) from table,在高密度的插入请求下,是有可能出问题的,返回错误值

last_insert_id说明

从名字可以看出,last_insert_id即为最后插入的id值,根据mysql的官方手册说明,它有2种使用方法

一是不带参数:last_insert_id(),这种方法和auto_increment属性一起使用,当往带有‘auto_increment'属性字段的表中新增记录时,last_insert_id()即返回该字段的值,大家可试下(我已经验证过);
二是带有表达式:如上面介绍的last_insert_id(value+1),它返回的是表达式的值,即‘value+1';
##################################
last_insert_id() 自动返回最后一个insert或 update 查询中 auto_increment列设置的第一个表发生的值。

mysql的last_insert_id的注意事项:

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

mysql> select last_insert_id();

        -> 100

使用这函数向一个给定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语句变得简单。

mysql> insert into t values

    -> (null, ‘mary'), (null, ‘jane'), (null, ‘lisa');

mysql> select * from t;

| id | name |

+—-+——+

|  1 | bob  |

|  2 | mary |

|  3 | jane |

|  4 | lisa |

mysql> select last_insert_id();  //这就是我要说明的关键问题。

| last_insert_id() |

|                2 |

虽然将3 个新行插入 t, 对这些行的第一行产生的 id 为 2, 这也是 last_insert_id()返回的值。

以上所述就是本文的全部内容了,希望大家能够喜欢。

请您花一点时间将文章分享给您的朋友或者留下评论。我们将会由衷感谢您的支持!

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网