📜  实体约束、引用约束和语义约束之间的区别

📅  最后修改于: 2021-09-13 02:00:24             🧑  作者: Mango

关系数据库中的数据以表格的形式存储。表格使数据看起来井井有条。然而,在某些情况下,我们在处理数据时可能会遇到诸如重复之类的问题。我们可能希望对数据执行规则以避免此类技术问题。这些规则称为约束。约束可以定义为必须对数据强制执行以避免错误的规则。约束分为三种:实体约束、引用约束和语义约束。下面列出了这三个约束之间的差异:

1.实体约束:
这些约束在一张表中给出。实体约束是主键、外键、唯一。

例子 :

create table student (rollnumber int primary key, name varchar2(30), course varchar2(10));
Insert into student values(111, 'ABC', 'Chemical');
Insert into student values(112, 'JJP', 'Mech');
Rollnumber Name Course
111 ABC Chemical
112 JJP Mech

这些值被插入到表中。假设插入了下面给出的值:

Insert into student values(111, 'MAB', 'EEE');

它给出了一个错误,因为 roll-number 是强制执行的主键约束,避免重复。这些约束确保在表中保持唯一性以避免重复。

2. 引用约束:
这些约束用于引用其他表以对数据实施条件。广泛使用的引用约束是外键。

例子 :

create table marks (rollnumber int, name varchar2(30), course varchar2(30)
references student, marks int);

创建一个表格,约束条件是分数应该只奖励给那些正在学习学生表格中规定的课程的学生。如果用户尝试输入不存在的值,则会返回错误。

3.语义约束:
数据类型是在表中强制执行的语义约束。数据类型帮助数据根据其类型进行分离。

例子 :
名称是不同字母的组合。我们可以将 name 列放在 char 数据类型中,但 char 不满足条件,因此 varchar 最好用于 name。

name varchar2(30);

实体约束、引用约束和语义约束的区别:

Characteristics Entity constrints Referential constraints Semantic constraints
Definition Entity constraints are posed within a table. Referential constraints are enforced with more than one table. Semantic constraints are enforced on the values of a specific attribute .
Kinds The entity constraints are: unique, primary key, NULL. The referential constraints are foreign key. The semantic constraints are the datatypes.
Description These constraints are used to enforce uniqueness in a table( while NULL is used to define no value) These constraints are used for referring to another table for analysis of the data. These constraints are used to divide a set of particular value based on a category.
Functions These constraints ensure non duplicate’s in a database. These constraints ensure that consistency of a database. These constraints ensure that values are categorized accordingly to avoid confusions.
Syntax Primary key:
create table( column1 datatype1 primary key…)
Foreign key:
create table( column1 datatype1 references tablename…)
column1 varchar2(30)
Examples No two students can be designated the same rollnumber. Rollnumber being referred to the marks table. Name is assigned to varchar2 with a precision of 50.