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

📅  最后修改于: 2021-08-24 04:34:08             🧑  作者: 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');

由于强制了滚动编号,因此产生了错误,因为它限制了主键约束,从而避免了重复操作。这些约束确保在表中保持唯一性以避免重复。

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

例子 :

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

创建一个表时要限制学生只对那些在学生表中规定的课程的学生给予相应的分数。如果用户尝试输入不存在的值,则会返回错误。

3.语义限制:
数据类型是表中强制执行的语义约束。数据类型有助于根据数据类型进行数据隔离。

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

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.