约束:数据库针对数据进行一系列的校验,如果发现插入的数据不符合约束中描述的校验规则,就会插入失败,为了更好的保证数据的正确性。 MySQL中主要主持6种完整性约束:
约束条件约束描述Primary Key主键约束,约束字段的值可以唯一的标识对应的记录Unique Key唯一约束,约束字段的值是唯一的Notnull Key非空约束,约束字段的值不能为空Default默认约束,约束字段的默认值Auto_Incremnet走到梦幻增加约束,约束字段的值自动增加Foreign Key外键约束,约束表与表之间的关系约束在作用上可以分为表级约束和劣迹约束两大类: 表级约束:可以约束表中任意一个或多个字段 列级约束:只能约束其中所在的某一个字段
非空约束规定表中的某一个字段的值不能为空(Null)。
注意: 空字符串""不是Null;0也不是Null创建表时为字段添加为空约束:
create table student( id int(11) not null, name varchar(20), score decimal(3,1) );该列的所有行数据时不能重复的
(1)使用列级约束添加
create table student( id int(11) unique, name varchar(20) unique, score decimal(3,1) );(2)使用表级约束添加
create table student( id int(11), name varchar(20), score decimal(3,1), unique(id,name) );注意:删除的是唯一约束,而不是该字段。
primary key可以相当于not null+unique 主键约束规定不能为空,且不能重复;其作用是约束表中的某个字段,以唯一的标识一条记录。
主键可以是单个字段也可以是多个字段的组合。 对于单个字段,主键的添加可以使用表级约束,也可以使用列级约束; 对于多个字段,主键的添加只能使用表级约束。 (1)为单个字段添加主键约束 ①使用列级约束为单个字段添加主键约束
create table student( id int(11) primary key, name varchar(20), score decimal(3,1) );②使用表级约束为单个字段添加主键约束
create table student( id int(11), name varchar(20), score decimal(3,1), primary key(id) );(2)为多个字段添加主键约束 多字段主键的含义是:主键由多个字段组合而成的。 只能使用表级约束。
create table student( school varchar(20), id int(11), name varchar(20), score decimal(3,1), primary key(school,id) );与非空约束一样,只能使用列级约束
auto_increment:自增主键 自增的特点: 如果表中没有任何记录,自增从1 开始 如果表中已经有记录了,自增从上一条记录往下自增 如果把中间的某个人数据删了之后,再插入数据,刚才删掉的自增主键的值不会被重复利用。
外键约束可以是两张表紧密地结合起来,特别是在进行修改或者删除的级联操作时,会保证数据的完整性。
下面用班级表class(主表)和学生表student(从表)来演示外键的创建
create table class( class_id int(3) primary key, class_name varchar(20), class_location varchar(50) ); create table student( stu_id int(10) primary key, stu_name varchar(10), stu_class int(3), constraint fk_stu_class foreign key(stu_class) references class(class_id) ); fk_stu_class:为外键约束名,也可将constraint fk_stu_class省略例如:给上述student表中的stu_class添加外键约束
alter table student add constraint fk_stu_class foreign key(stu_class) references class(class_id);注意:外键约束名不能重复。
我们都知道删除表使用drop table 表名;就可以删除掉表,但是这种方法是用来删除没有被其他表关联放入单表。如果要删除的表被其他表关联着(即删除的是一张主表的时候)就不能直接删除否则会报错。
有两种删除主表的方法 方法①:先删除从表student,再删除主表class 方法②:先删除从表student中的外键约束,再删除主表class 删除从表中的外键约束的时候,如果忘记了外键名可以使用"show create table 表名;"查看表的详细结构,来查看外键名。
方法①会影响从表中已存储的数据,方法②可以保证数据的安全性,所以选择方法②
alter table student drop foreign key fk_stu_class; drop table class;