一、常用的六大约束
1、primary key(主键约束):非空且唯一,每张表只能有一个主键
2、not null(非空约束):不能为空值
3、unique(唯一约束):值唯一,可以为空
4、default(默认约束):指定默认值
5、check(检查约束):保证某个字段满足条件
6、foreign key(外键约束):用于关联两张表,在相关联字段中主键所在的表就是主表(父表),外键所在的表就是从表(子表)。如果同一个属性字段x在主表中是主键,而在从表中不是主键,则字段称为从表的外键。
二、创建表时的列级约束、表级约束区别
1、列级约束:
语法:定义列时指定约束 -->字段名 数据类型 约束条件
支持的约束条件:主键、非空、唯一、默认、检查
不支持的约束条件:外键
不能自定义约束名
create table if not exists major(
id int primary key,
name varchar(20) not null
);
create table if not exists stu(
id int primary key, #主键约束
name varchar(20) unique not null, #唯一约束、非空约束
gender char(1) default '男', #默认约束
age int check(age between 0 and 100), #检查约束
majorid int,
constraint fk_majorid foreign key(majorid) references major(id) #外键约束
);
2、表级约束:
语法:声明所有字段之后再添加约束条件 --> constraint 约束名 约束条件(字段名)
支持的约束条件:主键、唯一、检查、外键
不支持的约束条件:非空、默认
能够自定义约束名
create table if not exists stu(
id int ,
name varchar(20) not null,
gender char(1) default '男',
age int ,
majorid int,
#添加约束条件
contraint pk_id primary key(id), #主键约束
contraint un_name unique(name), #唯一约束
contraint ck_gender check(gender in('男','女')), #检查约束
constraint fk_majorid foreign key(majorid) references major(id) #外键约束
);
三、不同约束条件的alter添加、删除语法
1、主键约束 --列级和表级都支持
表级添加约束:alter table 表名 add primary key(字段名);
例如: alter table stu add primary key(id);
列级添加约束:alter table 表名 modify 字段名 类型 primary key;
例如: alter table stu modify id int primary key;
删除约束:alter table 表名 drop primary key;
例如:alter table stu drop primary key;
2、非空、默认约束 --只支持列级
列级添加约束:alter table 表名 modify 字段名 数据类型 [not null | default 默认值];
例如:alter table stu modify name varchar(20) not null; --非空
alter table stu modify gender char(1) default '男'; --默认
删除约束:alter table 表名 modify 字段 数据类型;
例如:alter table stu modify name varchar(20) ; --非空
alter table stu modify gender char(1); --默认
3、唯一、检查约束 --列级和表级都支持
表级添加约束:alter table 表名 add constraint 约束名 [unique|check] 字段名;
例如: alter table stu add constraint un_name unique(name);
alter table stu add constraint ck_age check(age between 0 and 100);
列级添加约束:alter table 表名 modify 字段名 数据类型 [unique|check];
例如: alter table stu modify name unique;
alter table stu modify age check(age between 0 and 100);
删除约束:alter table 表名 drop [index|check] 约束名;
例如: alter table stu drop index un_name; --删除唯一约束(删除索引)
alter table stu drop check ck_age;
4、外键约束 --只支持表级
表级添加约束:alter table 表名 add constraint 约束名 [foreign key] 字段名;
例如:alter table stu constraint fk_majorid foreign key(majorid) references major(id);
删除约束:alter table 表名 drop [foreign key] 约束名;
例如:alter table stu drop foreign key fk_majorid;