📜  主键和外键的区别

📅  最后修改于: 2021-09-08 16:30:43             🧑  作者: Mango

首要的关键:
主键用于确保特定列中的数据是唯一的。它是一列不能有 NULL 值。它要么是现有的表列,要么是数据库根据定义的顺序专门生成的列。

例子:参考图——
STUD_NO 和 STUD_PHONE 都是关系 STUDENT 的候选键,但可以选择 STUD_NO 作为主键(只有一个候选键)。

外键:
外键是关系数据库表中的一列或一组列,它提供两个表中数据之间的链接。它是一列(或多列)引用另一个表的一列(通常是主键)。

例子:参考图——
STUDENT_COURSE 中的 STUD_NO 是 STUDENT 关系中 STUD_NO 的外键。

数字:

让我们看看主键和外键的区别:

S.NO. PRIMARY KEY FOREIGN KEY
1 A primary key is used to ensure data in the specific column is unique. A foreign key is a column or group of columns in a relational database table that provides a link between data in two tables.
2 It uniquely identifies a record in the relational database table. It refers to the field in a table which is the primary key of another table.
3 Only one primary key is allowed in a table. Whereas more than one foreign key are allowed in a table.
4 It is a combination of UNIQUE and Not Null constraints. It can contain duplicate values and a table in a relational database.
5 It does not allow NULL values. It can also contain NULL values.
6 Its value cannot be deleted from the parent table. Its value can be deleted from the child table.
7 It constraint can be implicitly defined on the temporary tables. It constraint cannot be defined on the local or global temporary tables.