MySQL LAST_INSERT_ID() 函数有何用途?
MySQL LAST_INSERT_ID() 函数用于获取 AUTO_INCREMENT 最近产生的序列号。
示例
在此示例中,我们创建了一个名为“Student”的表,该表有一个 AUTO_INCREMENT 列。我们在“Name”列中插入两个值,当我们使用 INSERT_LAST_ID() 函数时,它返回最近产生的序列号,即 2。
mysql> Create table Student(Id INT PRIMARY KEY NOT NULL AUTO_INCREMENT, Name Varchar(5)); Query OK, 0 rows affected (0.13 sec) mysql> Insert into student(Name) Values('Raman'); Query OK, 1 row affected (0.06 sec) mysql> Insert into student(Name) Values('Rahul'); Query OK, 1 row affected (0.07 sec) mysql> Select* from student; +----+-------+ | Id | Name | +----+-------+ | 1 | Raman | | 2 | Rahul | +---+-------+ 2 rows in set (0.00 sec) mysql> Select Last_insert_id(); +------------------+ | Last_insert_id() | +------------------+ | 2 | +------------------+ 1 row in set (0.00 sec)
广告