2012-03-17 93 views
3

假设我有一个带自动递增ID字段的MySQL表,然后插入3行。然后,我删除第二行。现在桌子上的ID变成1,3。我可以让MySQL来纠正这个问题,并且不必编写程序就可以做到这一点吗?删除自动增量中的差距

+1

这是不是主键的意图。如果您需要连续编号,则不要查看主键。你想达到什么目的? – 2012-03-17 22:17:04

+0

...(继续从伊恩伍德)如果你想序列编号,而不是PK的,使用'rowid'。 – slashmais 2012-03-17 22:19:08

+0

我试图从1,2,4,5,7,8等改变行ID。到1,2,3,4,5,6等。 – 2012-03-17 22:27:40

回答

5

MySQL不会让你改变一个自动索引列的索引一旦创建它。我所做的是删除自动索引列,然后添加一个具有相同名称的新索引,mysql将索引新生成的列而不留空白。只有在自动索引与其余数据不相关但仅用作更新和删除的参考的表上执行此操作。

比如最近我就这么做了含有谚语一个表,当我更新或删除一个谚语,但我需要自动索引是连续的谚语通过拉出只使用自动索引列随机数在1和谚语计数之间,在序列中有空位可能导致随机数指向一个不存在的索引。

HTH

+0

但我在其他表中的一些相关的数据相对于自动增量id作为外键,,,然后我将如何做到这一点? – 2014-01-11 10:00:38

+0

@ReNiShAR请参阅http://stackoverflow.com/a/5437720/14660 – Schwern 2015-02-13 19:52:44

0

The Access Ten Commandments引用(它可以扩展到其他RDBMS:“不可使用自动编号(或自动增量)如果该字段是为了有意为你的用户”

我能想到的(只使用MySQL的)的唯一的选择是:

  1. 创建触发器,增加了行号列(不是主键
  2. 创建一个过程来删除行和更新的行数(我不能让与触发器这项工作,对不起)

例子:

create table tbl_dummy(
    id int unsigned not null auto_increment primary key, 
    row_number int unsigned not null default 0, 
    some_value varchar(100) 
); 

delimiter $$ 

-- This trigger will add the correct row number for each record inserted 
-- to the table, regardless of the value of the primary key  
create trigger add_row_number before insert on tbl_dummy 
for each row 
begin 
    declare n int unsigned default 0; 
    set n = (select count(*) from tbl_dummy); 
    set NEW.row_number = n+1; 
end $$ 

-- This procedure will update the row numbers for the records stored 
-- after the id of the soon-to-be-deleted record, and then deletes it. 
create procedure delete_row_from_dummy(row_id int unsigned) 
begin 
    if (select exists (select * from tbl_dummy where id = row_id)) then 
     update tbl_dummy set row_number = row_number - 1 where id > row_id; 
     delete from tbl_dummy where id = row_id; 
    end if; 
end $$ 

delimiter ; 

请注意,您”我们将被迫逐一删除记录,并且您将被迫获取要删除的记录的正确主键值。

希望这有助于