数据库五大约束

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_32623363/article/details/87955249

所谓约束,其实就是一种保障,比如一个属性添加了主键约束,那么就强制保障了它的唯一性和非空性,请带着这样正确的理解去阅读后文。

数据库有五大约束,分别是:

  • 主键约束(Primay Key Coustraint):唯一,非空
  • 唯一约束 (Unique Counstraint):唯一,可以为空,但即便为空也只能有一个
  • 检查约束 (Check Counstraint) :申明该列数据的取值范围(如:年龄、性别等)
  • 默认约束 (Default Counstraint) :设置默认值
  • 外键约束 (Foreign Key Counstraint) : 关于外键的约束

主键约束

主键约束的要求是“唯一,非空”,因此主键不需要、也不能再设置唯一约束了。

另外,主键可以设置自动增长,而且,主键不一定是自动增长的,但自动增长的一定是主键。

设置主键的方式为:在定义列的时候再后面加上primary key
比如:

create table a(
	id int,
	constraint c_id primary key (id)
);

唯一约束

形如:

create table a(
	id int,
	constraint c_id unique(id)
);

检查约束

会在更新数据时检查数据插入或修改后是否符合约束条件,如果不符合则会导致更新失败。
形如:

create table a(
	age int,
	constraint c_age check(age>=0 && age<=150)
);

默认约束

就是当插入或修改一个字段后,如果某一个分量为null,则自动填充为默认值。
形如:

create table a(
	age int,
	constraint c_age defaule(18) for age
);

外键约束

外键约束定义的就是外键的关系。
形如:

create table 成绩表(
	studentid int,
	courseid int,
	grade int,
	constraint c_studentid Foreign key(studentid) References Student(id),
	constraint c_courseid Foreign key(courseid) References Course(id)
);

当然还可以动态地对约束进行操作,这里就不一一举例了,想详细了解约束的操作,推荐这篇博客:https://www.cnblogs.com/willingtolove/p/9215330.html#_label6

参考资料:
https://www.cnblogs.com/wcl2017/p/7043939.html
https://www.cnblogs.com/willingtolove/p/9215330.html#_label6
https://www.cnblogs.com/waj6511988/p/7027127.html

猜你喜欢

转载自blog.csdn.net/qq_32623363/article/details/87955249