The primary key id is reset after deleting data in MySQL

The primary key id is reset after deleting data in MySQL

Create database

create database db1;
use db1;
create table user3(
 	id int primary key auto_increment,
 	username varchar(16) not null unique ,
 	password varchar(16) not null,
 	createDatetime date
);

insert into user3 (username,password,createDatetime) values
("张伟","pass1","2019-07-11"),("王伟","pass2","2019-07-11"),
("王芳","pass3","2019-07-12"),("李伟","pass4","2019-07-11"),
("王秀英","pass5","2019-07-12"),("李秀英","pass6","2019-07-11"),
("李娜","pass7","2019-07-10"),("张秀英","pass8","2019-07-10"),
("刘伟","pass9","2019-07-12"),("张敏","pass10","2019-07-10");



Create data table

use db1;
create table user3(
 	id int primary key auto_increment,
 	username varchar(16) not null unique ,
 	password varchar(16) not null,
 	createDatetime date
);

Add data to the data table

insert into user3 (username,password,createDatetime) values
("张伟","pass1","2019-07-11"),("王伟","pass2","2019-07-11"),
("王芳","pass3","2019-07-12"),("李伟","pass4","2019-07-11"),
("王秀英","pass5","2019-07-12"),("李秀英","pass6","2019-07-11"),
("李娜","pass7","2019-07-10"),("张秀英","pass8","2019-07-10"),
("刘伟","pass9","2019-07-12"),("张敏","pass10","2019-07-10");

Select the last row of data to delete and insert new data

delete from user3 where password="pass10";

insert into user3 (username,password,createDatetime) values
("张三","pass","2019-7-13"),("李四","pass52","2019-7-10")

At this time, it was found that the newly inserted data id failed to start from 10.

[External link image transfer failed. The source site may have an anti-hotlinking mechanism. It is recommended to save the image and upload it directly (img-ecutRHNh-1588666290700) (C:\Users\hq0749a\AppData\Roaming\Typora\typora-user-images\ 1588223935639.png)]

To achieve the id output in order, we need to initialize the id and reset it

alter table user3 drop id;
alter table user3 add id int not null primary key auto_increment first;

After running, we can find that id is output in sequence again
[External link image transfer failed. The source site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-HNs9GVGC-1588666290705) (C:\Users\hq0749a\AppData\Roaming\Typora\typora-user-images\ 1588224107478.png)]

Guess you like

Origin blog.csdn.net/weixin_45609519/article/details/105934148