10、约束
什么是约束?
给表的字段添加约束,目的是为了保证数据的合法性、有效性、完整性。
常见约束类型:
1、非空: not null 约束的字段不能为NULL
2、唯一: unique 约束的字段不能重复,但是可以为NULL
3、主键: primary key 约束的字段既不能为NULL,也不能重复 (这个最重要) 4、外键: foreign key (多表连接用)
一 非空约束
就是这个字段必须给值,不给会报错。
not null 没有表级约束,只有列级约束,只能添加在列后面
二 唯一约束 (不能重复 可以为NULL)
1)列级约束(添加在字段后面)
//1 给某一列或多个列单独添加
drop table if exists user; create table user ( id int primary key, user_name varchar(255) unique, password varchar(255) unique);
2)表级约束(单独添加)
//2 给两个列或多个列联合添加一个约束 drop table if exists user; create table user( id int, user_name varchar(100), password varchar(100), unique(user_name,password)//只要用户名和密码加起来不重复就OK ); insert into user (1,'zhangsan',123456),(2,'zhangsan',1234); select * from user;
三 主键约束
主键的特点:
不能为空(NULL) 不能重复。
一张表的主键约束只能有一个
主键的作用
设计三范式,第一范式就要求任何一张表都应该有主键。
主键值是这行记录在这张表当中的唯一标识。(就像一个人的身份证号码一样。)
相关术语
主键约束: primary key
主键字段: id字段添加primary key之后,id字段就是主键字段
主键值: id字段中的每一个值都是主键值
主键分类
按主键数量划分
单一主键:最常用,推荐的
复合主键:多个字段联合起来添加一个主键约束。(不推荐)违背了设计三范式。
按主键性质划分
自然主键:最好就是一个和业务没有任何联系的自然数。(推荐)
业务主键:主键值和系统的业务挂钩,比如用银行卡或身份证做主键。(不推荐)
语法:
//1 列级约束 drop table if exists user; create table user( id int primary key, user_name varchar(100), password char(32) ); //2 表级约束 drop table if exists user; create table user( id int, user_name varchar(100), password char(32), primary key(id) );
主键自增:
drop table if exists user;
create table user (
id int primary key auto_increment,//主键自增 从1开始 递增1
user_name varchar(100));
四 外键约束 (myisam引擎不支持)
父子表
a表中的某个字段 引用了b表的某个字段,我们称a为子表,b为父表。
操作顺序:
1、删除数据:先删除子表 再删除父表
2、添加数据:先添加父表 再添加子表
3、建表顺序:先建父表 再建子表
4、删表顺序:先删子表 再删父表
建表语句:班级表 t_class 学生表 t_student
//建表必须选择innodb引擎
drop table if exists t_class;
drop table if exists t_student;
create table t_class(
id int primary key auto_increment comment '主键',
cno int unique comment '班级编号',
cname varchar(200) comment '班级名称'
)ENGINE=innodb;
create table t_student(
id int primary key auto_increment comment '主键',
sno int unique comment '学生编号',
sname varchar(50) comment '学生姓名',
class_no int,
foreign key(class_no) references t_class(cno)
)ENGINE=innodb;
insert into t_class (cno,cname) values(110,'九一小学五年一班');
insert into t_class (cno,cname) values(111,'九一小学五年二班');
insert into t_class (cno,cname) values(112,'九一小学五年上班');
insert into t_student(sno,sname,class_no) values (11406,'张子涵',110);
insert into t_student(sno,sname,class_no) values (11407,'赵海燕',111);
insert into t_student(sno,sname,class_no) values (11408,'付瓜瓜',112);
insert into t_student(sno,sname,class_no) values (11409,'牛小芳',113);//这条数据添加不成功 外键生效了
错误代码:ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`work`.`t_student`, CONSTRAINT `t_student_ibfk_1` FOREIGN KEY (`class_no`) REFERENCES `t_class` (`cno`))
外键值可以为null
外键字段引用其他表的某个字段的时候,被引用的字段必须是主键吗?
注意:被引用的字段不一定是主键,但至少具有unique约束。

浙公网安备 33010602011771号