ntroduction to MySQL foreign key

A foreign key is a field in a table that matches another field of another table. A foreign key places constraints on data in the related tables, which enables MySQL to maintain referential integrity.

Let’s take a look at the following database diagram in the sample database.

We have two tables: customers and orders. Each customer has zero or more orders and each order belongs to only one customer. The relationship between customers table and orders table is one-to-many, and it is established by a foreign key in the orders table specified by the customerNumber field. The customerNumber field in the orders table relates to the customerNumber primary key field in the customers table.

The customers table is called parent table or referenced table, and the orders table is known as child table or referencing table.

A foreign key can be a column or a set of columns. The columns in the child table often refer to the primary key columns in the parent table.

A table may have more than one foreign key, and each foreign key in the child table may refer to a different parent table.

A row in the child table must contain values that exist in the parent table e.g., each order record in the orders table must have a customerNumber that exists in the customers table. Multiple orders can refer to the same customer therefore, this relationship is called one (customer) to many (orders), or one-to-many.

Sometimes, the child and parent tables are the same. The foreign key refers back to the primary key of the table e.g., the following employees table:

The reportTo column is a foreign key that refers to the employeeNumber column which is the primary key of the employees table to reflect the reporting structure between employees i.e., each employee reports to anther employee and an employee can have zero or more direct reports. We have a specific tutorial on the self-join to help you query data against this kind of table.

The reportTo foreign key is also known as recursive or self-referencing foreign key.

Foreign keys enforce referential integrity that helps you maintain the consistency and integrity of the data automatically. For example, you cannot create an order for a non-existent customer.

In addition, you can set up a cascade on delete action for the customerNumber foreign key so that when you delete a customer in the customers table, all the orders associated with the customer are also deleted. This saves you time and efforts of using multiple DELETE statementsor a DELETE JOIN statement.

The same as deletion, you can also define a cascade on update action for the customerNumber foreign key to perform the cross-table update without using multiple UPDATE statements or an UPDATE JOIN statement.

In MySQL, the InnoDB storage engine supports foreign keys so that you must create InnoDB tables in order to use foreign key constraints.

Creating foreign keys for tables

MySQL creating foreign key syntax

The following syntax illustrates how to define a foreign key in a child table in CREATE TABLE statement.

CONSTRAINT constraint_name
FOREIGN KEY foreign_key_name (columns)
REFERENCES parent_table(columns)
ON DELETE action
ON UPDATE action
1
2
3
4
5
CONSTRAINT constraint_name
FOREIGN KEY foreign_key_name (columns)
REFERENCES parent_table(columns)
ON DELETE action
ON UPDATE action

Let’s examine the syntax in greater detail:

  • The CONSTRAINT clause allows you to define constraint name for the foreign key constraint. If you omit it, MySQL will generate a name automatically.
  • The FOREIGN KEY clause specifies the columns in the child table that refers to primary key columns in the parent table. You can put a foreign key name after FOREIGN KEY clause or leave it to let MySQL create a name for you. Notice that MySQL automatically creates an index with the foreign_key_name name.
  • The REFERENCES clause specifies the parent table and its columns to which the columns in the child table refer. The number of columns in the child table and parent table specified in the FOREIGN KEY and REFERENCES must be the same.
  • The ON DELETE clause allows you to define what happens to the records in the child table when the records in the parent table are deleted. If you omit the ON DELETE clause and delete a record in the parent table that has records in the child table refer to, MySQL will reject the deletion. In addition, MySQL also provides you with actions so that you can have other options such as ON DELETE CASCADE that ask MySQL to delete records in the child table that refers to a record in the parent table when the record in the parent table is deleted. If you don’t want the related records in the child table to be deleted, you use the ON DELETE SET NULL action instead. MySQL will set the foreign key column values in the child table to NULL when the record in the parent table is deleted, with a condition that the foreign key column in the child table must accept NULL values. Notice that if you use ON DELETE NO ACTION or ON DELETE RESTRICT action, MySQL will reject the deletion.
  • The ON UPDATE clause enables you to specify what happens to the rows in the child table when rows in the parent table are updated. You can omit the ON UPDATE clause to let MySQL reject any updates to the rows in the child table when the rows in the parent table are updated. The ON UPDATE CASCADE action allows you to perform a cross-table update, and the ON UPDATE SET NULL action resets the values in the rows in the child table to NULL values when the rows in the parent table are updated. The ON UPDATE NO ACTION or UPDATE RESTRICT actions reject any updates.

MySQL creating table foreign key example

The following example creates a dbdemo database and two tables: categories and products. Each category has one or more products and each product belongs to only one category. The cat_id field in the products table is defined as a foreign key with UPDATE ON CASCADE and DELETE ON RESTRICT actions.

CREATE DATABASE IF NOT EXISTS dbdemo;

USE dbdemo;

CREATE TABLE categories(
cat_id int not null auto_increment primary key,
cat_name varchar(255) not null,
cat_description text
) ENGINE=InnoDB;

CREATE TABLE products(
prd_id int not null auto_increment primary key,
prd_name varchar(355) not null,
prd_price decimal,
cat_id int not null,
FOREIGN KEY fk_cat(cat_id)
REFERENCES categories(cat_id)
ON UPDATE CASCADE
ON DELETE RESTRICT
)ENGINE=InnoDB;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
CREATE DATABASE IF NOT EXISTS dbdemo;
 
USE dbdemo;
 
CREATE TABLE categories(
   cat_id int not null auto_increment primary key,
   cat_name varchar(255) not null,
   cat_description text
) ENGINE=InnoDB;
 
CREATE TABLE products(
   prd_id int not null auto_increment primary key,
   prd_name varchar(355) not null,
   prd_price decimal,
   cat_id int not null,
   FOREIGN KEY fk_cat(cat_id)
   REFERENCES categories(cat_id)
   ON UPDATE CASCADE
   ON DELETE RESTRICT
)ENGINE=InnoDB;

Adding a foreign key to a table

MySQL adding foreign key syntax

To add a foreign key to an existing table, you use the ALTER TABLE statement with the foreign key definition syntax above:

ALTER table_name
ADD CONSTRAINT constraint_name
FOREIGN KEY foreign_key_name(columns)
REFERENCES parent_table(columns)
ON DELETE action
ON UPDATE action;
1
2
3
4
5
6
ALTER table_name
ADD CONSTRAINT constraint_name
FOREIGN KEY foreign_key_name(columns)
REFERENCES parent_table(columns)
ON DELETE action
ON UPDATE action;

MySQL adding foreign key example

Now, let’s add a new table named vendors and change the products table to include the vendor id field:

USE dbdemo;

CREATE TABLE vendors(
vdr_id int not null auto_increment primary key,
vdr_name varchar(255)
)ENGINE=InnoDB;

ALTER TABLE products
ADD COLUMN vdr_id int not null AFTER cat_id;

1
2
3
4
5
6
7
8
9
USE dbdemo;
 
CREATE TABLE vendors(
    vdr_id int not null auto_increment primary key,
    vdr_name varchar(255)
)ENGINE=InnoDB;
 
ALTER TABLE products
ADD COLUMN vdr_id int not null AFTER cat_id;

To add a foreign key to the products table, you use the following statement:

ALTER TABLE products
ADD FOREIGN KEY fk_vendor(vdr_id)
REFERENCES vendors(vdr_id)
ON DELETE NO ACTION
ON UPDATE CASCADE;
1
2
3
4
5
ALTER TABLE products
ADD FOREIGN KEY fk_vendor(vdr_id)
REFERENCES vendors(vdr_id)
ON DELETE NO ACTION
ON UPDATE CASCADE;

Now, the products table has two foreign keys, one refers to the categories table and another refers to the vendors table.

Dropping MySQL foreign key

You also use the ALTER TABLE statement to drop foreign key as the following statement:

ALTER TABLE table_name
DROP FOREIGN KEY constraint_name;
1
2
ALTER TABLE table_name
DROP FOREIGN KEY constraint_name;

In the statement above:

  • First, you specify the table name from which you want to remove the foreign key.
  • Second, you put the constraint name after the DROP FOREIGN KEY clause.

Notice that constraint_name is the name of the constraint specified when you created or added the foreign key to the table. If you omit it, MySQL generates a constraint name for you.

To obtain the generated constraint name of a table, you use the SHOW CREATE TABLE statement as follows:

SHOW CREATE TABLE table_name;
1
SHOW CREATE TABLE table_name;

For example, to see the foreign keys of the products table, you use the following statement:

SHOW CREATE TABLE products;
1
SHOW CREATE TABLE products;

The following is the output of the statement:

CREATE TABLE products (
prd_id int(11) NOT NULL AUTO_INCREMENT,
prd_name varchar(355) NOT NULL,
prd_price decimal(10,0) DEFAULT NULL,
cat_id int(11) NOT NULL,
vdr_id int(11) NOT NULL,
PRIMARY KEY (prd_id),
KEY fk_cat (cat_id),
KEY fk_vendor(vdr_id),

CONSTRAINT products_ibfk_2
FOREIGN KEY (vdr_id)
REFERENCES vendors (vdr_id)
ON DELETE NO ACTION
ON UPDATE CASCADE,

CONSTRAINT products_ibfk_1
FOREIGN KEY (cat_id)
REFERENCES categories (cat_id)
ON UPDATE CASCADE
) ENGINE=InnoDB;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
CREATE TABLE products (
  prd_id int(11) NOT NULL AUTO_INCREMENT,
  prd_name varchar(355) NOT NULL,
  prd_price decimal(10,0) DEFAULT NULL,
  cat_id int(11) NOT NULL,
  vdr_id int(11) NOT NULL,
  PRIMARY KEY (prd_id),
  KEY fk_cat (cat_id),
  KEY fk_vendor(vdr_id),
 
  CONSTRAINT products_ibfk_2
  FOREIGN KEY (vdr_id)
  REFERENCES vendors (vdr_id)
  ON DELETE NO ACTION
  ON UPDATE CASCADE,
 
  CONSTRAINT products_ibfk_1
  FOREIGN KEY (cat_id)
  REFERENCES categories (cat_id)
  ON UPDATE CASCADE
) ENGINE=InnoDB;

The products table has two foreign key constraints: products_ibfk_1 and products_ibfk_2

You can drop the foreign keys of the products table by using the following statement:

ALTER TABLE products
DROP FOREIGN KEY products_ibfk_1;

ALTER TABLE products
DROP FOREIGN KEY products_ibfk_2;

1
2
3
4
5
ALTER TABLE products
DROP FOREIGN KEY products_ibfk_1;
 
ALTER TABLE products
DROP FOREIGN KEY products_ibfk_2;

MySQL disabling foreign key checks

Sometimes, it is very useful to disable foreign key checks e.g., when you import data from a CSV file into a table. If you don’t disable foreign key checks, you have to load data into a proper order i.e., you have to load data into parent tables first and then child tables, which can be tedious. However, if you disable the foreign key checks, you can load data in any orders.

Another example is that, unless you disable the foreign key checks, you cannot drop a table that is referenced by a foreign key constraint. When you drop a table, any constraints that you defined for the table are also removed.

To disable foreign key checks, you use the following statement:

SET foreign_key_checks = 0;
1
SET foreign_key_checks = 0;

And of course, you can enable it using the statement below:

SET foreign_key_checks = 1;
1
SET foreign_key_checks = 1;

In this tutorial, we have covered a lot about MySQL foreign key. We also introduced you to some very handy statements that allow you to manage foreign keys effectively in MySQL.

http://www.mysqltutorial.org/mysql-foreign-key/

MySQL Foreign Key的更多相关文章

  1. mysql FOREIGN KEY约束 语法

    mysql FOREIGN KEY约束 语法 作用:一个表中的 FOREIGN KEY 指向另一个表中的 PRIMARY KEY. DD马达 说明:FOREIGN KEY 约束用于预防破坏表之间连接的 ...

  2. MySQL—FOREIGN KEY

    作用:保持数据一致性,完整性.实现一对一或一对多关系.(学习的过程中,老师说,实际的生产中,一般不使用物理上的外键约束的,都是使用逻辑上的外键约束) 要求: 父表与子表的存储引擎必须相等,而且只能是I ...

  3. mysql foreign key(外键) 说明与实例

    一,什么是foreign key,及其完整性 个人觉得,foreign key就是表与表之间的某种约定的关系,由于这种关系的存在,我们能够让表与表之间的数据,更加的完整,关连性更强.关于完整性,关连性 ...

  4. mysql foreign key 外键

    ALTER TABLE `fd_rel_customer_doctor` ADD CONSTRAINT `FK_fd_rel_customer_doctor_1` FOREIGN KEY (`CUST ...

  5. 更改具有Foreign key约束的表

    1.Foreign key 说明: foreign key(外键) 建立起了表与表之间的约束关系,让表与表之间的数据更具有完整性和关联性.设想,有两张表A.B,A表中保存了许多电脑制造商的信息,比如联 ...

  6. MySQL主从复制中断,报“Error on master: message (format)='Cannot delete or update a parent row: a foreign key constraint fails' error code=1217” 错误

    前几天,发现从库挂了,具体报错信息如下: 分析思路 1. 因为我采用的是选择性复制,只针对以下几个库进行复制: card,upay,deal,monitor,collect.所以,不太可能出现对于sa ...

  7. MYSQL外键(Foreign Key)的使用

    在MySQL 3.23.44版本后,InnoDB引擎类型的表支持了外键约束.外键的使用条件:1.两个表必须是InnoDB表,MyISAM表暂时不支持外键(据说以后的版本有可能支持,但至少目前不支持): ...

  8. mysql 外键(FOREIGN KEY)

    最近有开始做一个实验室管理系统,因为分了几个表进行存储·所以要维护表间的关联··研究了一下MySQL的外键. (1)只有InnoDB类型的表才可以使用外键,mysql默认是MyISAM,这种类型不支持 ...

  9. MySQL添加外键时报错 ERROR 1215 (HY000): Cannot add foreign key constraint

    1.数据类型      2.数据表的引擎 数据表 mysql> show tables; +------------------+ | Tables_in_market | +--------- ...

随机推荐

  1. Windows环境下修改Oracle实例监听IP地址

    Windows环境下修改Oracle实例监听IP地址. 配置文件路径:<ORACLE_HOME>\NETWORK\ADMIN 如:C:\Oracle11gR2\product\11.2.0 ...

  2. java单元测试注释执行顺序

    JUnit4通过注解的方式来识别测试方法.目前支持的主要注解有: @BeforeClass 全局只会执行一次,而且是第一个运行 @Before 在测试方法运行之前运行 @Test 测试方法 @Afte ...

  3. Mac OS 下安装和配置 maven

    1. 安装 Maven 前的必须准备 需先安装 Java 环境 下载合适的 JDK 配置 JDK 环境变量 JAVA_HOME:为 JDK 安装目录 Path:为 JDK/bin 目录 测试是否成功: ...

  4. 【intellij idea】汇总

    1 右键无法创建,找不到scala class https://blog.csdn.net/u011513853/article/details/52896230 2 缩进 https://jingy ...

  5. poj3662 Telephone Lines

    思路: 二分+最短路.最短路也可以用来计算从a到达b所需的边权不超过x的边的数量. 实现: #include <cstdio> #include <cmath> #includ ...

  6. Kickstart Round D 2017 : A

    思路: 动态规划. large数据的时间范围很大,无法设计入状态中.转换思路为定义dp[i][j]为当前在景点i,并且已经游览了j个景点所花费的最小时间,这种思想与leetcode45类似.于是转移方 ...

  7. lua使用lfs.dll库进行文件操作

    在项目开发中,为了提高开发效率往往需要开发一些辅助工具.最近在公司用lua帮拓展了一个资源扫描的工具,这个工具的功能就是从原始demo下指定目标资源文件,对该文件进行读取并筛选过滤一遍然后拷贝到最终d ...

  8. swift potocol 作为参量时函数的派发顺序

    1.检查protocol本体是否声明调用函数: 2.如果没有,检查protocol扩展是否有该函数:如果扩展中也没有,报错: 3.如果本体声明了函数,使用动态派发机制进行派发:扩展中的实现位于最末位.

  9. at, batch, atq, atrm - 排队、检查或删除以后要执行的作业

    总览 at [-V] [-q 队列] [-f 文件] [-mldbv] 时间 at -c 作业 [作业...] atq [-V] [-q 队列] [-v] atrm [-V] 作业 [作业...] b ...

  10. Win7 与win10绘制桌面壁纸的区别

    win7使用csrss.exe绘制壁纸. win10使用explorer.exe绘制壁纸.