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


alter table tt auto_increment=8;

表tt

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

刪除兩條數據,再次添加后斷層了

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

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

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

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

如何重新從8開始呢?這個時候AUTO_INCREMENT已經變為了11,不管你刪除多少條,它都將從11開始增加。我們修改一下這個數值。

mysql > show create table tt;
+-------+---------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table | Create Table                                                                                                                                            |
+-------+---------------------------------------------------------------------------------------------------------------------------------------------------------+
| tt    | CREATE TABLE `tt` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'id',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8mb4 |
+-------+---------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

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

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

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM