数据库外键是什么意思
Jun 06, 2016 pm 08:42 PM数据库外键是什么意思?
外键(FK)是用于建立和加强两个表数据之间的链接的一列或多列。通过将保存表中主键值的一列或多列添加到另一个表中,可创建两个表之间的链接。这个列就成为第二个表的外键。
当创建或更改表时可通过定义 FOREIGN KEY 约束来创建外键。
例如,数据库 pubs 中的 titles 表与 publishers 表有链接,因为在书名和出版商之间存在逻辑联系。
titles 表中的 pub_id 列与 publishers 表中的主键列相对应。titles 表中的 pub_id 列是到 publishers 表的外键。
扩展资料:
保持数据一致性,完整性,主要目的是控制存储在外键表中的数据。 使两张表形成关联,外键只能引用外表中的列的值或使用空值。
学号在成绩表(表2)中是主键,在学生表(表1)中是外键。如果不使用外键,表1的学号字段插了一个值(比如20140999999),但是这个值在表2中并没有,这个时候,数据库允许插入,并不会对插入的数据做关系检查。
然而在设置外键的情况下,插入表1学号字段的值必须要求在表1的学号字段能找到。 同时,如果要删除表2的某个学号字段,必须保证表2中没有引用该字段值的列,否则就没法删除。
这就是所谓的保持数据的一致性和完整性。如右图,如果表1还引用表2的某个学号,却把表1中的这个学号删了,表2就不知道这个学号对应的学生是哪个学生。
更多相关技术文章,请访问PHP中文网!

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP's big data structure processing skills

How to optimize MySQL query performance in PHP?

How to use MySQL backup and restore in PHP?

How to insert data into a MySQL table using PHP?

How to fix mysql_native_password not loaded errors on MySQL 8.4

How to use MySQL stored procedures in PHP?

How to create a MySQL table using PHP?

Detailed tutorial on establishing a database connection using MySQLi in PHP
