MySql(8)--MySQL 数据库信息插入及自动编号

一:为表的所有列插入数据
以上篇文章创建的四个表为例
insert into bookcategory(category_id,category,parent_id)values(1,’计算机’,0);
点击这个按钮,我们就能编辑查看刚刚的语句
这里写图片描述
也可以省略列的名称插入,但是插入循序必须争取
insert into bookcategory values(2,’医学’,0);
这里写图片描述

二:为表的部分列插入数据
insert into readerinfo(card_id,name,tel)values(‘210210199901011111’,’张飞’,’13566661111’);
这里写图片描述

三:同时插入多条记录
insert into bookcategory(category_id,category,parent_id)values(3,’编程语言’,1),(4,’数据库’,1),(5,’儿科学’,2);
这里写图片描述

四:复制一个表的一部分信息插入到另一个表当中
我们复制test表中的一部分信息id大于5的部分插入到bookcategory表中,
这里写图片描述
insert into bookcategory select * from test where id>5;
这里写图片描述

五:设置自动编号
如果不设置自动编号,我们就要手动编号,可能还会出错
这里写图片描述

比如我们创建一个临时的bookcategory_temp
这里的auto_increment就是自增列,自增列的默认初始值为1,以此增加
create table bookcategory_tmp(
category_id int primary key auto_increment,
category varchar(20) not null unique,
parent_id int not null
);
或者
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);
insert into bookcategory_tmp(category,parent_id)values(‘计算机’,0);
然后查看表格,自动添加编号就出来了
这里写图片描述
如果我们一开始定义auto_increment=5;那么医学这一列的起始值就为5了

– 去掉自增列
alter table bookcategory_tmp modify category_id int;

– 添加自增列
alter table bookcategory_tmp modify category_id int auto_increment;

– 修改自增列的起始值
alter table bookcategory_tmp auto_increment = 15;
这里写图片描述

六:设置自动编号(关联关系)
如果两个表直接有关联关系,想要给其中一个表添加自动编号,必须先解除关联关系,然后再添加自动编号
这里写图片描述

– 删除图书信息表的外键
alter table bookinfo drop foreign key fk_bcid;

– 为图书类别表添加自动编号的功能
alter table bookcategory modify category_id int auto_increment;

– 恢复关联
alter table bookinfo add constraint fk_bcid foreign key(book_category_id)references bookcategory(category_id);

猜你喜欢

转载自blog.csdn.net/weixin_42350428/article/details/81707547