一、约束条件
约束类型 | 关键字 |
---|---|
默认约束 | default '值' |
非空约束 | not null |
唯一约束 | unique key |
自增长约束 | auto_increment |
主键约束 | primary key |
外键约束 | foreign key |
1.1 默认约束(default '默认值')
初始值设置,插入记录时,如果没有明确为字段赋值,则自动赋予默认值
create table `tb_name`(
`field_name` data_type default "default_value",...
);
1.2 非空约束(not null)
插入数据时, 非空约束字段必须插入值
create table `tb_name`(
`field_name` data_type not null,...
);
1.3 唯一约束(unique key)
create table `tb_name`(
`field_name` data_type unique key,...
);
1.4 自增长约束(auto_increment)
create table tb_name(
field_name data_type auto_increment,...
);
-- 一张表中只有一个字段自增长。非空且唯一的字段才可以添加自增长约束,
1.5 主键约束(primary key)
create table tb_name(
field_name data_type primary key,...
); -- 主键要求 非空且唯一。
-- 联合主键
create table `tb_name`(
`field_name1` data_type,
`field_name2` data_type,
primary key(field_name_1, field_name_2)
)
1.6 外键约束(foreign key (当前表的字段) references 参照表表名(被参照字段))
- 保持数据的一致性、完整性,实现一对一或一对多关系。
- 外键必须关联到键上面去,一般情况是,关联到另一张表的主键。
- 因为一个表只在一类信息。用外键来做参照,保证数据的一致性,可以减少数据冗余。
create table `tb_name`(
`field_name1` data_type,
`field_name2` data_type,
constraint AB_id foreign key (当前表的字段) references 参照表表名(被参照字段)
);
-- 1. 通过(当前表的字段)关联到(参照表被参照字段)中,然后,可以重新命名为 AB_id(其中constraint AB_id 可不写)
-- 2. 外键约束定义,当前表表中的字段,只能添加参照表参照字段中已有的数据。
-- 3. 参照表中的被参照字段的数据,不能被修改和删除。
-- (在当前表中有的数据,被参照表不能修改和删除, 想要删除要先把当前表中的删除,才能删除参照表被参照字段的数据)
二、表关系
表关系有三种
一对一
一对多
多对多
下面就学生系统数据库设计表为例
2.1 一对一
- 用外键的方式,把两个主键关联
- 举例,学生表中有学号、姓名、学院,但学生还有写比如电话,家庭地址等信息,这些信息不会放在学生表中,会新建一个学生的详细信息表来储存。
- 这时的学生表和学生的详细信息两者的关系就是一对一的关系,因为一个学生只有一条详细信息,用主键加主键的方式来实现这种关系
-- 建立学生表
create table student(
id int primary key auto_increment,
name varchar(20) not null
);
-- 建立详细学生表
create table student_details(
id_x int primary key,
sex varchar(20) not null,
age int,
height int,
foreign key(id_x) references student(id) -- 通过外键将字段id_x关联到student表的id字段
);
-- 说明:学生表和学生详情表通过student.id 和student_deatails.id_x关联,形成一对一关系,只能插入主键相同的数据
2.2 一对多
通常情况下,学校中一个学院可以有很多学生,而一个学生只属于某一个学院
学院与学生之间的关系就是一对多的关系,通过**外键关联**来实现这种关系
-- 创建学院表
create table college(
id int primary key,
subjects varchar(10) not null
);
#创建学院的学生表
create table vip(
id_v int primary key auto_increment, -- 学生的id
name_v varchar(10) not null, -- 学生名字
id_w int not null, -- 所属学院id,只能添加已有的学院id
foreign key(id_w) references college(id) -- 外键
);
2.3 多对多
举例,学生要报名选修课,一个学生可以报名多门课程,一门课程有很多学生报名,那么学生表和课程表两者就形成了多对多关系
对于多对多关系,需要创建中间表实现
-- 课程表, 课程是属于学院的, 所以用外键关联到学院表
create table course(
id int primary key auto_increment,
name_c varchar(10),
id_c int not null,
foreign key(id_c) references college(id)
);
-- 创建选课表(中间表), 一个字段用外联关联到学生表, 一个关联到课程表
create table choose(
id_stu int,
id_cor int,
primary key(id_stu,id_cor), #联合主键
foreign key(id_stu) references vip(id_v), #关联到学生表的id_v字段
foreign key(id_cor) references course(id) #关联到课程表的id字段
);