约束的目的:确保表中数据的完整性
常见的约束类型:
主键约束(Primary key constraint):要求主键列数据唯一,并且不能为空
唯一约束(Unique constraint):要求该列唯一,允许为空,但只能出现一个空值
检查约束(Check constraint):某列取值范围限制、格式限制等,如有关年龄的约束
默认约束(default constraint):某列的默认值,如我们的男性学员较多,相别默认为“男”
外键约束(foreign key constraint):用于两表间建立关系,需要指定引用主表的那列
添加约束的语法:
alter table 表名
add constraint 约束名 约束类型 具体的约束说明
约束名的取名规则推荐采用:约束类型_约束字段
主键(primary key)约束:如 PK_stuNo
唯一(unique)约束:如 UQ_stuId
默认(default)约束:如 DF_stuAddress
检查(check)约束:如 CK_stuAge
外键(foreign key)约束:如 FK_stuNo
添加约束示例:
alter table stuInfo
add constraint pk_stuNo primary key(stuNo)
alter table stuInfo
add constraint uq_stuId unique (stuId)
alter table stuInfo
add constraint df_stuAddress default('地址不详') for stuAddress
alter table stuInfo
add constraint ck_stuAge check(stuAge between 15 and 40)
alter table stuMarks --从表
add constraint fk_stuNo foreign key(stuNo) references stuInfo(stuNo) --主表
删除约束的语法:
alter table 表名
drop constraint 约束名
浙公网安备 33010602011771号