常见的约束有五大类型:
唯一性约束 unique
非空约束 not null
主键约束 primary key
外键约束 foreign key
检查约束 check
唯一性约束 unique
对相应的列建立索引,是唯一性索引,用于提升查询效率,该列要求值唯一。
建表时设置
create table t_user(id int,name varchar(20) unique,sex char(1),phone varchar(11));
建表后添加,uk_stu_name为约束的名字
alter table student add constraint uk_stu_name unique(name);
非空约束 not null
要求改列的值不能是null值,必须显示的插入或者更新一个值非空约束只能是列级约束
建表时设置
create table t_user(id int,name varchar(20) unique,sex char(1) not null,phone varchar(11));
建表后添加
alter table student modify name varchar(30) not null;
主键约束 primark key
要求改列的值是非空且唯一的。
建表时设置
create table t_user(id int primary key auto_increment,name varchar(20) unique,sex char(1) not null,phone varchar(11));
建表后添加
alter table student add constraint pk_stu_name primary key (id);
外键约束 foreign key
用于两表之间建立关系的。在从表中建立一个字段列添加外键约束引用主表的主键值。
建表时设置,t_emp 表中的deptid 属性参照t_dept 表中的id列,t_emp为从表,t_dept为主表
create table t_emp (id int primary key auto_increment,name varchar(200),sex char(1),salary double(10,2),deptid int,foreign key(deptid) references t_dept(id) );
建表后添加
alter table t_emp add constraint fk_emp_dept foreign key (deptid) references t_dept(id);
检查约束 check
mysql不支持 Oracle支持的
create table t_stu(id int primary key auto_increment,name varchar(20),age int check (age>20));