繁体   English   中英

获取mysql中任何表的最后插入的id

[英]Get last inserted id of any table in mysql

我正在通过php导入.sql文件。 我的.sql文件包含多个表,并且我想要特定表的最后插入的ID。 那么,如何通过表名获取任何表的最后插入ID?

知道如何获取ID吗? 请不要建议,通过选择查询获取ID以获取MAX ID。

我们有。

id | value
1  |  10
3  |  20

然后我们插入2 | 15 2 | 15 ,所以它变成了

id | value
1  |  10
2  |  15
3  |  20

(提醒一下,我们有一个.sql文件,而不是实时连接)

现在您想知道,最后一个是2 如果是这样,那是不可能的。 .sql文件不保留此类信息,仅保留裸数据和一些元数据。

这可以在mysql和mysqli中完成。

 $conn = mysqli_connect($servername, $username, $password, $dbname);
    $sql = "INSERT INTO MyGuests (firstname, lastname, email)
    VALUES ('abc', 'xyz', 'abc@example.com')";
    if (mysqli_query($conn, $sql)) {
        $last_id = mysqli_insert_id($conn);}

在MySQL中

       mysql_connect($servername, $username, $password);
       mysql_select_db($dbname);
        $sql = "INSERT INTO MyGuests (firstname, lastname, email)
        VALUES ('abc', 'xyz', 'abc@example.com')";
        if (mysql_query($sql)) {
            $last_id = mysql_insert_id();}

只要定义了auto_increment ,就可以从information_schema.tables检索到最后插入的自动增量ID:

select IF(auto_increment = 1, 
          'No row has been inserted', 
          auto_increment - @@auto_increment_increment) As LastInsertedId
from information_schema.tables 
where table_schema = 'DBName' and table_name = 'TableName';

试试这些功能

如果您使用的是PDO,请使用PDO::lastInsertId

如果您使用的是Mysqli,请使用mysqli::$insert_id

但是,如果需要,请使用mysql_insert_id

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM