MySQL补

表结构修改

- 1.修改表名:alter table 原表名 rename to 新表名;
alter table college rename to coll;
- 2.修改字段名:alter table student change 原字段名 新字段名 data_type(字段类型);
alter table student change id num varchar(8);
- 3.修改字段类型:alter table student modify id varchar(4);#强烈建议不要这样用
- 4.添加字段:alter table student add hobby varchar(64);
- 5.删除字段:alter table student drop hobby;

约束条件

- 约束条件一般用在创建表的时候
- 1.默认约束:default,插入数据时,没有赋值,自动赋予默认值,没默认值,默认为null,  alter table student add hobby enum("xiaoge","dalong") default "xiaoge";
- 2.非空约束:not null,限制一个字段的值不能为空,insert时必须为该字段赋值,特别的是enum(a,b)被修饰时默认是a,非空字符不能与null合用,一般与default配合使用
alter table student add addr varchar(128) not null default "zhaodong";
- 3.唯一约束:限制一个字段的值不能重复,确保字段中的值唯一
alter table student modify id int unique key;
- 4.主键:primary key,通常每张表都需要一个主键来体现唯一性,每张表里只有一个主键,主键=非空+唯一
alter table student modify id int primary key;
- 5.自增长:auto_increment要求用在主键上,自动编号,和主键组合使用,一个表只能有一个自增长,被删掉的不会自动添加
alter table score modify id int primary key auto_increment;
- 6.外键:foreign key,保证多表数据的一致性,外键能关联另一张表的主键,外键表有的,主键表一定有;主键表没有的,外键表一定没有

事物

- 为了保证操作的一致性,(例如:转账,减少A的钱增加B的钱等),要么都成功,要么都不成功
- mysql默认开启事务物,事物只支持数据库引擎
mysql事物的两种方式:
1.直接用set来改变mysql的自动提交模式
	- set autocommit = 0	#禁止自动提交
	- set autocommit = 1	#开启自动提交
2.用begin,rollback,commit来实现
 	- 步骤:
 	1.begin开始一个事物,检测是否都成功
 	if 都成功了:
 		commit	#提交
 	else:
 		rollback	#回滚

数据库表关系

- MySQL精髓是操作表,表中存储的是有关系的数据,表和表也有关联
- 1.一对一:A表中一条数据和B表中一条数据有关系
- 2.多对一(一对多):A表中多条数据和B表中一条数据有关系
- 3.多对多:A表中多条数据和B表中多条数据有关系
- 多对多在mysql中会用一个中间表C,A表和C表是一对多,B表和C表是一对多,所以A表和C表形成多对多
- 用于保持数据一致性,完整性
- MySQL用外键来实现这个约束

案例:

- 1.学院表,2.学生表,3.课程表,4.选课表
学院:python,java,c++
学生:zs,ls,ww,zl,hmm
学科:python_web,python_spider,python_analysis,jzee,qt
选课:zs:python_web,python_spider,python_analysis
	   ls:python_web
	   ww:python_spider
	   zl:jzee
	   hmm:qt
1.学院表: create table college(id int primary key auto_increment,name varchar(32));		创建学院表
insert into college(name) values("python"),("java"),("c++");	
2.学生表: create table student( id int primary key auto_increment, name varchar(32), c_id int, foreign key(c_id) references college(id));
insert into student(name,c_id) values ("zs",1),("ls",1),("ww",1),("zl",2),("hmm",3);
#此处用到外键关联学院表的主键,1,2,3,分别对应学院表python,java,c++
3.课程表:create table course(id int primary key auto_increment, name varchar(32),c_id int,foreign key(c_id) references college(id));
 insert into course(name,c_id) values ("python_web",1),("python_spider",1),("python_analysis",1),("jzee",2),("qt",3);
 4.选课表:create table enroll( stu_id int, cou_id int, primary key(stu_id,cou_id), foreign key(stu_id) references student(id), foreign key(cou_id) references course(id));
 insert into enroll(stu_id,cou_id) values(1,1),(1,2),(1,3),(2,1),(3,2),(4,4),(5,5);
 select s.id,s.name,c.name,cl.name from student as s,course as c,enroll as e,college as cl where e.stu_id=s.id and e.cou_id=c.id and s.c_id=cl.id;
#用一张表,内容是:学生id,学生姓名,报名课程名称

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/xiaogeldx/article/details/84669512