簡體   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