在实践中,你必须非常小心,并且真的知道你在做什么,因为填充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