2012-03-17 96 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 ; 

請注意,您」我們將被迫逐一刪除記錄,並且您將被迫獲取要刪除的記錄的正確主鍵值。

希望這有助於