我有一個簡單的問題。獲取最近一次輸入的行的AUTO_INCREMENT
我正在將信息放入MySQL中,並且我有一個auto_increment字段,我將獨自離開。
如何獲得剛剛輸入的行中的auto_increment字段的值?
我有一個簡單的問題。獲取最近一次輸入的行的AUTO_INCREMENT
我正在將信息放入MySQL中,並且我有一個auto_increment字段,我將獨自離開。
如何獲得剛剛輸入的行中的auto_increment字段的值?
SELECT MAX(that_field) AS last_auto_increment_value FROM that_table;
OR
SELECT auto_increment -1 AS last_auto_increment_value
FROM information_schema.tables
WHERE table_name='that_table'
AND table_schema = 'that_database';
OR
mysql_insert_id() //in PHP
mysql_query("INSERT INTO mytable (product) values ('kossu')");
printf("Last inserted record has id %d\n", mysql_insert_id());
這裏的三種不同的方法,從三個常用庫,可以與MySQL(MySQL和mysqli的,PDO)
mysql_insert_id(...)
[程序功能]
mysqli::$insert_id
[OOP接口物業]
PDO::lastInsertId(...)
[OOP方法]
PDO :: lastInsertId - 返回最後插入的行或列值
爲什麼要使用這些複雜的查詢,而不是mysql_insert_id或PDO等同的ID? – stUrb
'SELECT MAX()'會返回最大的值,它可能是也可能不是最後一次插入運行的值。用'mysql_insert_id()'它會返回從'INSERT'創建的id,因爲它在同一連接實例上 –
@stUrb我沒有仔細閱讀這個問題。 – cypher