MySQL数据库复习(3)------约束

写在最前面:本博文如有错误,还望指出,谢谢

其它相关文章

MySQL数据库复习(1)----单表查询sql语句
MySQL数据库复习(2)----多表查询和增删改sql语句
MySQL数据库复习(4)----存储引擎,事务,索引,视图和设计三范式

八、约束

1.什么是约束?常见的约束有哪些?

在创建表的时候,可以给表的字段添加相应的约束,添加约束的目的是为了保证表中数据的合法性、有效性、完整性
常见的约束有:
非空约束(not null)
唯一约束(unique)
主键约束(primary key):约束的字段既不能为NULL,也不能重复,简称PK
外键约束(foreign key):简称FK
检查约束(key):Oracle数据库有check约束,但是MySQL没有,目前MySQL不支持该约束

2.非空约束 not null

3.唯一性约束(unique)

唯一性约束修饰的字段具有唯一性,不能重复。但可以为NULL
例:给某一列添加unique

drop table if exists t_user;
create table t_user
(
	id int,
	username varchar(255) unique
);
insert into t_user values(1,’zhangsan’);
insert into t_user values(2,’zhangsan’);

执行这段程序的时候会报错
例:给两个列或多个列添加unique
注意以下两者的区别,上面的为两个字段联合起来添加唯一性约束,下面的为两个字段分别添加唯一性约束

drop table if exists t_user;
create table t_user
(
	id int,
	username varchar(255),
	usercode varchar(255),
	unique(usercode,username)
);
drop table if exists t_user;
create table t_user
(
	id int,
	username varchar(255) unique,
	usercode varchar(255) unique
);

4.列级约束和表级约束

列级约束:直接在列后面添加约束
表级约束:声明完之后再添加约束
注意:not null约束只有列级约束,没有表级约束

5.主键约束

1)怎么给一张表添加主键约束?

drop table if exists t_user;
create table t_user
(
	id int primary key,
	username varchar(255),
	usercode varchar(255)
);

id是主键,因为添加了主键约束,主键当中的数据不能为NULL,也不能重复
2)主键相关的术语?
主键约束,主键字段,主键值
3)主键有什么作用?
表的设计三范式中有要求,第一范式就要求任何一张表都应该有主键
主键的作用:主键值是这行记录在这张表当中的唯一标识(就像身份证号一样)
4)主键的分类
根据主键字段和字段数量来划分:
单一主键:
复合主键:多个字段联合起来添加一个主键约束
根据主键性质来划分:
自然主键:主键值是一个和业务没有关系的自然数(推荐使用)
业务主键:主键值和系统的业务挂钩,比如用银行卡卡号做主键(不推荐用)
注意:一张表的主键约束只能有一个
5)使用表级约束方式定义主键:

drop table if exists t_user;
create table t_user
(
	id int,
	username varchar(255),
	usercode varchar(255),
	primary key(id)
);

6)mysql提供主键值自增(重要)

drop table if exists t_user;
create table t_user
(
	id int primary key auto_increment,
	username varchar(255),
	usercode varchar(255)
);

在这里,id字段自动维护一个自增的数字,从1开始,以1递增
补充:Oracle当中也提供了一个自增机制叫做:序列(sequence)

6.外键约束

1)关于外键约束的相关术语:
外键约束:foreign key
外键字段:添加有外键约束的字段
外键值:外键字段中的每一个值
2)业务背景
请设计数据库表用来维护学生和班级的信息
第一种方案:一张表存储所有数据
缺点:冗余(不推荐)
第二种方案:两张表存储数据,班级表和学生表
t_class 班级表
有两列:cno(pk),cname
t_student 学生表
有三列:sno(pk),sname,cno(fk)
最后一个字段添加了外键约束,添加了外键约束之后,学生表中的cno不能随便写,必须写班级表中cno中有的值才行
在上述表中,t_student中的cno字段引用t_class表中的cno字段,此时t_student表叫做子表。t_class表叫做父表
删表时先删子表,再删父表
添加数据的时候,先添加父表,再添加子表
创建表时先创建父表再创建子表
删除数据的时候,先删除子表,再删除父表

建表语句:

drop table if exists t_student;
drop table if exists t_class;
create table t_class(
	cno int,
	cname varchar(255),
	primary key(cno)
);
create table t_student(
	sno int,
	sname varchar(255),
	classno int,
	foreign key(classno) references t_class(cno)
);

3)外键可以为NULL
4)外键字段引用其他表的某个字段时,这个字段不一定是主键,但是必须有唯一性
本笔记网课来源:https://www.bilibili.com/video/BV1fx411X7BD

猜你喜欢

转载自blog.csdn.net/weixin_46841376/article/details/112657894