MySQL >= 8.0 のオートインクリメント値の取得
2025.12.26
MySQL 8.0 以上ではそれ以前のオートインクリメントの取得方法では正しい数値が得られない場合があります。
MySQL >= 8.0 では仕様が変わりインクリメント値を取得する際にキャッシュ(的な)値を参照する仕様になったため正確な値ではなく、テーブルに新データを追加後も何回取得処理を実行しても同じ数値が返ってきます。
通常は次のインクリメント値が何かはあまり気にせず処理することで問題ありませんが、特定の処理においては事前に正しいインクリメント値の取得が必要なケースがあり、そういった場合のための処理が以下となります。
次のコードはWordPressでusersテーブルのオートインクリメントを取得する例です。
オートインクリメント取得のSQLを実行する前に SET SESSION information_schema_stats_expiry=0; を実行することで保存されたオートインクリメント値を返すのではなく、現在の実際のインクリメント値を返すようにします。
functions.php 等に記述する際、以下のように一手間挟むことで正確な値の取得が可能となります。
/**
* This function is used to get the current auto increment for the target table.
* @param string $table The target table name, such as "users" or "posts". No prefix is required.
* @return integer|false Returns the current increment value, or false if unable to obtain it.
*/
function get_auto_increment($table)
{
// Getting auto-increment for MySQL >= 8.0 in WordPress
global $wpdb;
$pre_query = $wpdb->prepare('SET SESSION information_schema_stats_expiry = %d', 0);
$pre_db_result = $wpdb->query($pre_query);
if ($pre_db_result === false) {
// Database error
}
$table = $wpdb->prefix . $table;
$sql = $wpdb->prepare('SHOW TABLE STATUS LIKE %s', $table);
$table_status = $wpdb->get_results($sql);
$increment = ($table_status) ? (int) $table_status[0]->Auto_increment : false;
return $increment;
}
$current_increment = get_auto_increment('users');
参考
MySQL 8.0 information_schema_stats_expiry について