mysql如何设置自动增长id列

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/swjtu2014112194/article/details/86359855

参考:
https://blog.csdn.net/WxQ92222/article/details/79956403

我使用的是navicat软件来可视化mysql。
实际上navicat可以直接设置自动增长的,在设计表时只要添加类型为int或bigint的列,然后底下就有自动增长的选项了。
在这里插入图片描述

如果你想看看命令行怎么设置的话,就可以往下看。

查看当前数据库的自增长设置

SHOW VARIABLES LIKE 'auto_inc%';

这条SQL语句作用是查看当前数据库的自增长设置。
在这里插入图片描述
auto_increment_increment是自增长的步长。
auto_increment_offset是自增长开始的值

如何为一张表增加自增列?

现在有一张表book。

alter table book add id BIGINT; -- 为book表增加一个名称为id,类型为bigint的列
alter table book change id id BIGINT not null auto_increment primary key; -- 将id列设置为主键并且自增

修改自增长设置

SET @@auto_increment_increment=3; -- 将自动增长步长设为3
SET @@auto_increment_offset=4; -- 将自动增长初始值设为4

在这里插入图片描述
在这里插入图片描述
然后:

alter table book drop column id; -- 删除book表之前的id列
alter table book add id BIGINT; -- 添加id列
alter table book change id id BIGINT not null auto_increment primary key; -- 设置id为自增长列,主键

猜你喜欢

转载自blog.csdn.net/swjtu2014112194/article/details/86359855