How to reorder a primary key?

前端 未结 5 1009
小蘑菇
小蘑菇 2021-01-01 06:21

I have a table of 5700 records. The primary key is an integer. Now I noticed that some values are missing. Like this:

100 data
101 data 
102 data
104 data


        
相关标签:
5条回答
  • 2021-01-01 06:49

    Not sure about one command, but you can do it in four commands:

    CREATE TABLE `temp` SELECT * FROM `orig_tbl`;
    TRUNCATE `orig_tbl`;
    -- counter doesn't reset in some old versions
    ALTER TABLE `orig_tbl` AUTO_INCREMENT = 1; 
    -- now we omit primary key column to let it seal the holes
    INSERT INTO `orig_tbl` (`col1`, `col2`) SELECT `col1`, `col2` FROM `temp`;
    

    Unless you're doing this to make it easier to select records randomly, you really should rethink your approach.

    0 讨论(0)
  • 2021-01-01 06:51

    Another way, without truncating whole table:

    -- Make Backup of original table's content
    CREATE TABLE `orig_tbl_backup` SELECT * FROM `orig_tbl`;
    -- Drop needed column. 
    ALTER TABLE `orig_tbl` DROP `id`;
    -- Re-create it
    ALTER TABLE `orig_tbl` AUTO_INCREMENT = 1;
    ALTER TABLE `orig_tbl` ADD `id` int UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST;
    
    0 讨论(0)
  • 2021-01-01 06:54

    Try this:

    SET @var:=0;
    UPDATE `table` SET `id`=(@var:=@var+1);
    ALTER TABLE `table` AUTO_INCREMENT=1; 
    
    0 讨论(0)
  • 2021-01-01 06:55

    There is no point in doing this.

    IDs from deleted records are not re-used on purpose - to make sure that references from other tables to previously deleted records don't suddenly point to the wrong record, for example. It is not a good idea to try to change this.

    If you want a numbered list that has no holes, create a second int column that you re-order in your client program whenever necessary (i.e. when a record is deleted).

    0 讨论(0)
  • 2021-01-01 06:59

    I'd advise against messing with your PKs unless you really have no choice, it can cause breakage all over the place when that id column is referred by other tables. If the PK really tolerates no gaps, maybe the choice of PK was not ideal...

    If you really think you should do this (and are sure nothing will break in other tables):

    • create a table with the same structure as the original one, but use type serial for id
    • copy data without id into that copy table - you'll now have a copy of original with thanks to serial a nice gapless id field
    • empty original table (or faster, create an identical copy and drop original)
    • copy data from copy table into original table including id
    0 讨论(0)
提交回复
热议问题