在實踐中,你必須非常小心,並且真的知道你在做什麼,因爲填充id列中的'空白'可能會破壞整個數據庫或系統的參照完整性,表被其他表引用。否則,一個快速的方法是首先使用mysql填充現有行的'空'id,例如,使用phpMyAdmin,用類似於以下,確保表以升序id列排序之後:
SET @count = 0;
UPDATE the_table SET id = @count:= @count + 1;
#Then after this you do your insert operations.
以上將更新所有現有的IDS的順序,你插入的項目會只需將auto_incremented設置爲與表格中總行數相同的標識即可。
但是,如果你要離開已非空IDS完好無損,那麼你可以做這樣的事情在PHP中:
/* Assume that you want to insert into a table called the_table with columns id, col1, col2, col3 a new row with values for the three cols
$value1, $value2, $value3 respectively, using an existing 'gap' in the id numbering: */
/* Get an array of all present ids: */
$arr = [];
$q1 = mysqli_query($con,"SELECT id from the_table");
while(list($id) = mysqli_fetch_array($q1)){
$arr[] = $id;
}
/* Get the currently largest id in the table as $largest_id */
$q2 = mysqli_query($con,"SELECT MAX(id) from the_table");
list($largest_id) = mysqli_fetch_array($q2);
/* Loop through all integers up to $largest_id + 1 */
/* And do the insert operation just one time, once you find a number not in $arr */
/* Use the $not_yet_inserted variable to break out of the loop */
$not_yet_inserted = true;
for($j = 1; $j <= $largest_id + 1; $j += 1){
if(!in_array($j,$arr) && $not_yet_inserted){
mysqli_query($con,"INSERT INTO the_table (id, col1, col2,col3) values ('$j','$value1','$value3,'$value3'')");
$not_yet_inserted = false;
}
}
這是一個可怕的想法。相反,**詢問一個新問題**,解釋「您的要求」是什麼,並尋求如何使用由專業人員創建的自動遞增ID來滿足它的幫助。創建「你自己的」是一個非起動器。 – alexis