数据库的5种约束

版权声明:本博客为记录本人学习过程而开,内容大多从网上学习与整理所得,若侵权请告知! https://blog.csdn.net/Fly_as_tadpole/article/details/85276322

数据库五大约束

数据库中的五种约束及其添加方法

五大约束

1.—-主键约束(Primay Key Coustraint)唯一性,非空性,设置主键约束;

2.—-唯一约束(Unique Counstraint)唯一性,可以空,但只能有一个,设置唯一性约束,不能有重复值;

3.—-检查约束 (Check Counstraint) 对该列数据的范围、格式的限制(如:年龄、性别等)NOT NULL:设置非空约束,该字段不能为空;

4.—-默认约束 (Default Counstraint) 该数据的默认值
 

5.—-外键约束 (ForeignKey Counstraint) 需要建立两表间的关系并引用主表的列。

五大约束的语法示例

1.—-添加主键约束(将stuNo作为主键)

alter table stuInfo

add constraint PK_stuNo primary key (stuNo)

2.—-添加唯一约束(身份证号唯一,因为每个人的都不一样)

alter table stuInfo

add constraint UQ_stuID unique(stuID)

3.—-添加默认约束(如果地址不填默认为“地址不详”)

alter table stuInfo

add constraint DF_stuAddress default (‘地址不详’) for stuAddress

4.—-添加检查约束(对年龄加以限定 15-40岁之间)

alter table stuInfo

add constraint CK_stuAge check (stuAge between 15 and 40)

值得注意的是MYSQL所有引擎都不支持检查约束 

alter table stuInfo

add constraint CK_stuSex check (stuSex=’男’ or stuSex=’女′)

5.—-添加外键约束 (主表stuInfo和从表stuMarks建立关系,关联字段stuNo)

alter table stuInfo

add constraint FK_stuNo foreign key(stuNo)references stuinfo(stuNo)


 

MySQL中对三种约束的支持

猜你喜欢

转载自blog.csdn.net/Fly_as_tadpole/article/details/85276322
今日推荐