Filling Gaps in Auto-Increment Fields
Question: Is there a way to seamlessly fill gaps in auto-increment fields with new inserts?
Answer:
While it is generally not advisable to rely on auto-increment fields for ordering or semantic meaning, there are situations when filling these gaps may be desirable. In such cases, a MySQL feature can be utilized to create a new set of sequential IDs.
Create a temporary table using CREATE TEMPORARY TABLE NewIDs (NewID INT UNSIGNED AUTO INCREMENT, OldID INT UNSIGNED) and insert all existing IDs in ascending order:
INSERT INTO NewIDs (OldID) SELECT Id FROM OldTable ORDER BY Id ASC
This will create a mapping between old and new IDs.
To update the references in other tables, disable foreign key constraints:
SET foreign_key_checks = 0;
Then, update the Parent and Child tables:
UPDATE Parent, Child, NewIds SET Parent.ParentId = NewIds.Id, Child.ParentId = NewIds.Id WHERE Parent.ParentId = NewIds.ParentId AND Child.ParentId = NewIds.ParentId
Finally, re-enable foreign key checks:
SET foreign_key_checks = 1;
Drop the temporary table for cleanup:
DROP TABLE NewIds
It's important to note that this process should be used with caution, as modifying auto-increment fields can have implications for referential integrity and performance.
以上がMySQL の自動インクリメント フィールドのギャップを埋めることはできますか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。