Auto Increment after delete in MySQL

后端 未结 17 1782
醉酒成梦
醉酒成梦 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");
    
    0 讨论(0)
  • 2020-11-22 10:25

    here is a function that fix your problem

        public static void fixID(Connection conn, String table) {
    
        try {
            Statement myStmt = conn.createStatement();
            ResultSet myRs;
            int i = 1, id = 1, n = 0;
            boolean b;
            String sql;
    
            myRs = myStmt.executeQuery("select max(id) from " + table);
            if (myRs.next()) {
                n = myRs.getInt(1);
            }
            while (i <= n) {
                b = false;
                myRs = null;
                while (!b) {
                    myRs = myStmt.executeQuery("select id from " + table + " where id=" + id);
                    if (!myRs.next()) {
                        id++;
                    } else {
                        b = true;
                    }
                }
    
                sql = "UPDATE " + table + " set id =" + i + " WHERE id=" + id;
                myStmt.execute(sql);
                i++;
                id++;
            }
    
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    
    0 讨论(0)
  • 2020-11-22 10:26

    you can select the ids like so:

    set @rank = 0;
    select id, @rank:=@rank+1 from tbl order by id
    

    the result is a list of ids, and their positions in the sequence.

    you can also reset the ids like so:

    set @rank = 0;
    update tbl a join (select id, @rank:=@rank+1 as rank from tbl order by id) b
      on a.id = b.id set a.id = b.rank;
    

    you could also just print out the first unused id like so:

    select min(id) as next_id from ((select a.id from (select 1 as id) a
      left join tbl b on a.id = b.id where b.id is null) union
      (select min(a.id) + 1 as id from tbl a left join tbl b on a.id+1 = b.id
      where b.id is null)) c;
    

    after each insert, you can reset the auto_increment:

    alter table tbl auto_increment = 16
    

    or explicitly set the id value when doing the insert:

    insert into tbl values (16, 'something');
    

    typically this isn't necessary, you have count(*) and the ability to create a ranking number in your result sets. a typical ranking might be:

    set @rank = 0;
    select a.name, a.amount, b.rank from cust a,
      (select amount, @rank:=@rank+1 as rank from cust order by amount desc) b
      where a.amount = b.amount
    

    customers ranked by amount spent.

    0 讨论(0)
  • 2020-11-22 10:28
    ALTER TABLE foo AUTO_INCREMENT=1
    

    If you've deleted the most recent entries, that should set it to use the next lowest available one. As in, as long as there's no 19 already, deleting 16-18 will reset the autoincrement to use 16.


    EDIT: I missed the bit about phpmyadmin. You can set it there, too. Go to the table screen, and click the operations tab. There's an AUTOINCREMENT field there that you can set to whatever you need manually.

    0 讨论(0)
  • 2020-11-22 10:28

    You shouldn't be relying on the AUTO_INCREMENT id to tell you how many records you have in the table. You should be using SELECT COUNT(*) FROM course. ID's are there to uniquely identifiy the course and can be used as references in other tables, so you shouldn't repeat ids and shouldn't be seeking to reset the auto increment field.

    0 讨论(0)
  • 2020-11-22 10:29

    What you are trying to do is very dangerous. Think about this carefully. There is a very good reason for the default behaviour of auto increment.

    Consider this:

    A record is deleted in one table that has a relationship with another table. The corresponding record in the second table cannot be deleted for auditing reasons. This record becomes orphaned from the first table. If a new record is inserted into the first table, and a sequential primary key is used, this record is now linked to the orphan. Obviously, this is bad. By using an auto incremented PK, an id that has never been used before is always guaranteed. This means that orphans remain orphans, which is correct.

    0 讨论(0)
提交回复
热议问题