数据库SQL(五):Integrity Constraints(完整性约束)

文章目录

1、why

为什么要有完整性约束呢?
因为完整性约束可以保证用户修改数据库时不会破坏数据库的一致性,就是说不会将不满足应用需求的数据存入数据库。

2、what

Integrity Constraints are specified when schema is defined.
Integrity Constraints are checked when relations are modified.
也就是说,定义数据库schema的时候说明完整性约束,修改数据库表的时候检验是否违反了完整性约束。

完整性约束的类型:
key和foreign key是常用的的约束;
基于值的约束与应用数据管理需求相关,例如房价不能为负数,GPA不能超过4等
基于元组的约束:属性之间的约束
断言:一般指数据库中所有的表需要满足的约束,检测代价很大。

  • 单一关系上的约束:
    Not null,这个约束在应用层面经常遇到:注册时的必填项。

在这里插入图片描述

  • Check子句完成值的约束,这个例子说明了semester这个属性的取值为枚举的四个值,尽管数据类型为varchar。
    在这里插入图片描述

  • Referential Integrity(引用完整性)
    Ensures that a value that appears in one relation for a given set of attributes also appears for a certain set of attributes in another relation.
    Example: If “Biology” is a department name appearing in one of the tuples in the instructor relation, then there exists a tuple in the department relation for “Biology”.
    Let A be a set of attributes. Let R and S be two relations that contain attributes A and where A is the primary key of S. A is said to be a foreign key of R if for any values of A appearing in R these values also appear in S.
    外码是一种数据的完整性约束,如果在department表中,某个department值没有出现过,则在instructor表中不能出现这个department值,即不能引用。总结就是,存在的才能被引用。

参照完整性约束的级联操作: on delete cascade/ on update cascade
外码依赖链:在链的一端做的删除或修改操作会影响整个链。

例题解释:定义course表时,其中的属性dept_name是外键,dept_name varchar(20) references department ,如果加入了on delete cascade和on update cascade声明,那么删除或修改department表中的记录导致这个参照完整性约束被违反,删除或修改不会被系统拒绝,而是对course表进行“级联”删除或修改。级联动作也可以是set null, set default

在这里插入图片描述

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值