Auto Increment after delete in MySQL

后端 未结 17 2161
醉酒成梦
醉酒成梦 2020-11-22 09:50

I have a MySQL table with a primary key field that has AUTO_INCREMENT on. After reading other posts on here I\'ve noticed people with the same problem and with varied answer

17条回答
  •  广开言路
    2020-11-22 10:23

    if($id == 1){ // deleting first row
                mysqli_query($db,"UPDATE employees  SET id=id-1 WHERE id>1");
            }
            else if($id>1 && $id<$num){ // deleting middle row
                mysqli_query($db,"UPDATE employees  SET id=id-1 WHERE id>$id");
            }
            else if($id == $num){ // deleting last row
                mysqli_query($db,"ALTER TABLE employees AUTO_INCREMENT = $num");
            }
            else{
                echo "ERROR";
            }
    
            mysqli_query($db,"ALTER TABLE employees AUTO_INCREMENT = $num");
    

提交回复
热议问题