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