数据约束
给表添加数据约束,从而约束用户操作表数据的行为。
1、默认值约束(default)
2、非空约束(not null)
3、唯一约束(unique)
4、主键约束(primary key)(唯一+非空)
5、自增长约束(auto_increment)
6、外键约束(foreign key)
1、默认值约束(default)
注:当前没有插入默认值字段的时候,默认值才会起作用
create table test(
name varchar(20),
gender varchar(2) default '男' ##当不插入gender的时候,分配一个‘男’的默认值
)
2、非空约束(not null)
create table test(
name varchar(20) not null,
gender varchar(2)
)
注:name字段一定要有值(不能不插入数据,不能是null)
1、直接在创建表的字段后使用 not null
2、在创建表后使用 alter table 表名 modify 字段名 类型 not null;
3、唯一约束(unique)
create table test(
id int unique,
name varchar(20)
)
注:id的值不能出现重复值。这时就要给id添加一个唯一约束。唯一约束不能约束null。
1、直接在创建表的字段后使用 unique
2、在创建表的语句后面使用 constraint 约束名 unique key(字段名);
3、在创建表后使用 alter table 表名 add constraint 约束名 unique key(字段名);
4、主键约束(primary key)(唯一+非空)
注:1、通常情况下,我们会给每张表都会设置一个主键字段,用来标记记录的唯一性
2、建议给每张张独立添加一个叫id的字段,把这个id字段设置成主键,用来作为记录的唯一性。
create table test(
id int primary key,
name varchar(20)
)
1、直接在创建表的字段后使用 primary key
2、在创建表的语句的最后面使用 constraint 约束名 primary key(字段名)
3、在创建表后使用 alter table 表名 add constraint 约束名 primary key(字段名);
5、自增长约束(auto_increment)
必须在主键基础上自增
create table student(
id int(4) zerofill primary key auto_increment, -- 自增长,从0开始 zerofill 零填充
name varchar(20)
)
注:自增长字段可以不赋值,自动递增,初始值0,每次递增1(数据库维护,不需要开发者管理)
insert into student(name) values('张三');
不能影响自增长约束:delete from student;
可以影响自增长约束:truncate table student;
6、外键约束(foreign key)
外键作用: 约束两种表的数据
数据会出现重复(冗余),如果数据出现冗余,那么会浪费数据库存储空间。
create table employee(
id int primary key auto_increment,
name varchar(20),
deptid int, ##references dept(id)
constraint employee_dept_fk foreign key(deptid) references dept(id)
-- 外键名称 外键字段 参考
)
1、直接在创建表的字段后使用 references 父表名(父表主键名)
2、在创建表的语句的最后面使用 constraint 约束名 foreign key(字段名) references 父表名(父表主键名)
3、在创建表后使用 alter table 表名 add constraint 约束名 foreign key(字段名) references 父表名(父表主键名) on delete set null on update cascade
级联技术
级联:当有了外键的时候,我们希望修改或删除数据的时候,修改或删除了主表的数据,同时能够影响父表的数据,这时就可以使用级联。
create table employee(
id int primary key auto_increment,
name varchar(20),
deptid int,
-- 添加级联修改: on update cascade
-- 添加级联删除: on delete cascade
constraint employee_dept_fk foreign key(deptid) references dept(id) on update cascade on delete cascade
-- 外键名称 外键字段 参考
)
alter table 表名 add constraint 约束名 foreign key(字段名) references 父表名(父表主键名) on delete set null on update cascade; --级联删除设置为null
数据库设计
数据库设计的三大范式
1、第一范式: 要求表的每个字段必须独立的不可分割的单元学生表: student name --违反第一范式
张三|狗娃
王含|张小含
select * from student where name like '%张%';
学生表: student name old_name --符合第一范式
张三 狗娃
王含 张小含
2、第二范式: 在第一范式的基础上,要求表的除主键以外的字段都和主键有依赖关系的。(一张表应该只表达一个意思)
员工表:employee
员工编号 员工姓名 部门名称 订单名称 --违反第二范式
员工编号 员工姓名 部门名称 --符合第二范式
订单编号 订单名称
3、第三范式: 在第二范式基础上,要求表的除主键外的字段都只能和主键有直接决定的依赖关系。
员工表:employee --违反第三范式(出现数据冗余)
员工编号 员工姓名 部门编号 部门名称
1 张三 1 软件开发部
2 李四 1 软件开发部
员工编号 员工姓名 部门编号
1 张三 1
2 李四 1
部门表: dept
部门编号 部门名称
1 软件开发部