为什么要设置自动编号:
如上图所示,类别编号如果不设置自动编号的话,则需要人为的进行编辑和插入。
设置表的属性值自动增加:
语法规则:
列名 数据类型 auto_increment
注:
auto_increment约束的字段可以是任何整数类型(tinyint,smallint,int等)
例子:
创建自动编号表:
create table bookcategory(
category_id int primary key auto_increment,
category varchar(20) not null unique,
parent_id int not null
);
自增列的初始值默认为1,每添加1条记录,自动增长1。
在建表时可用’auto_increment=n‘选项来指定一个自增的初始值。
向表中插入记录:
insert into bookcategory (category,parent_id) values('计算机',0);
这条语句中没有给category_id指定值,我们看一下查询表记录的结果:
表中的category_id自动变成了1.
在创建表时设置自动编号的初始值:
create table bookcategory_tmp(
category_id int primary key auto_increment,
category varchar(20) not null unique,
parent_id int not null
) auto_increment=5;
向表中插入记录:
insert into bookcategory_tmp (category,parent_id)values('医学’,0);
查看表记录时,category_id的值变成了5,往后每增加1条,编号自动+1:
如何为已存在的表增加自动编号列:
如果在创建表时没有为列指定自动编号,那么可以通过以下命令来修改:
create table bookcategory_tmp(
category_id int primary key,
category varchar(20) not null unique,
parent_id int not null
);
alter table bookcategory_tmp modify category int auto_increment;
修改自增列的起始值:
create table bookcategory(
category_id int primary key auto_increment,
category varchar(20) not null unique,
parent_id int not null
);
alter table bookcategory auto_increment=X;
修改后的auto_increment列起始值从X开始。
去掉自增列:
alter table bookcategory modify category_id int;
如果要添加自增列的表与其他表存在关联关系,那么首先要去掉关联关系以后,才可以修改表的自动编号列。
删除关联关系:
alter table 主表名 drop foreign key外键名;
然后再修改表的自动编号列:
alter table bookcategorymodify category_idint auto_increment;
然后再恢复两表之间的关联关系:
alter table bookinfo
add constraint fk_bcid
foreign key(book_category_id)
inferences bookcategory(category_id);
未完待续~
了解更多内容,请关注: