1. 程式人生 > >mysql自增主鍵在大量刪除後如何重新設定避免斷層

mysql自增主鍵在大量刪除後如何重新設定避免斷層

select * from tt;
+----+
| id |
+----+
|  1 |
|  2 |
|  3 |
|  4 |
|  5 |
|  6 |
|  7 |
|  8 |

|  9 |

delete from tt where id=8;
Query OK, 1 row affected (0.01 sec)


delete from tt where id=9;
Query OK, 1 row affected (0.01 sec)


>insert into tt values(null);
Query OK, 1 row affected (0.01 sec)


select * from tt;
+----+
| id |
+----+
|  1 |
|  2 |
|  3 |
|  4 |
|  5 |
|  6 |
|  7 |
| 10 |
+----+

看到新插入的記錄是在10開始的不是在8開始,如果想要在8開始,需要在刪除資料後,重置下自動增長的位置

delete from tt where id=10;
Query OK, 1 row affected (0.01 sec)


alter table tt auto_increment=8
    -> ;
Query OK, 0 rows affected (0.01 sec)
Records: 0  Duplicates: 0  Warnings: 0


insert into tt values(null);
Query OK, 1 row affected (0.00 sec)


select * from tt;
+----+
| id |
+----+
|  1 |
|  2 |
|  3 |
|  4 |
|  5 |
|  6 |
|  7 |
|  8 |
+----+
8 rows in set (0.01 sec)

看到在重新設定後,自增主鍵是在8開始了,這樣可以避免出現id斷層