First, the foreign key Introduction
Field represents a foreign key in the table is a reference to a field in another table. Resulting in the limitation of the foreign key in the dependent table data, so MySQL can maintain referential integrity.
Let's look at the sample database (yiibaidb) the following two database tables: customers
the ER and `orders`` of FIG.
The figure above there are two tables: customers
and orders
. Each customer zero or more orders, each order belongs to a customer. customers
Tables and orders
relationships between tables are many, and it is customerNumber
specified in the field orders
to establish a foreign key table (reference customers
table customerNumber
fields). orders
Table customerNumber
fields customers
table customerNumber
associated primary key field.
customers
Table called the parent table or the referenced table, orders
the table is called the child table or the referenced table.
Table can have multiple foreign keys, each foreign key in the child table may refer to a different parent table.
Child table row must contain a value present in the parent table, for example, orders
each order record in the table must customers
exist in the table customerNumber
. Therefore, multiple orders can refer to the same customers, so this relationship is called a (client) to many (orders) or one to many.
Sometimes, the child and parent tables are the same, a foreign key to return to the table's primary key.
reportTo
A reference column is employeeNumber
a foreign key column, employeeNumber
the column is employees
the primary key for the table to reflect the reporting structure between employees, i.e. employees and each employee reports sent to other employees can have zero or more direct reports. For information about how to use there, please refer to the self-ligation tutorials to help you to query data query based on this table.
reportTo
Also referred to as a recursive foreign key or foreign key from the referenced.
Foreign key implementation of referential integrity, can help you automatically maintain the consistency and integrity of data. For example, you can not create orders for customers that do not exist.
Additionally, you can customerNumber
delete the foreign key to cascade, so that customers
when you delete the customer, all orders associated with the client will also be deleted table. This saves you use multiple DELETE statements , or DELETE JOIN statements time and effort.
And remove the same, may also be a customerNumber
foreign key definitions cascade update operations to perform cross-table update, without the use of a plurality UPDATE statement or UPDATE the JOIN statement.
In MySQL, InnoDB storage engines support foreign keys, so you must create the InnoDB table to use foreign key constraints.
Second, create a foreign key
MySQL create a foreign key syntax
The following syntax shows how the CREATE TABLE definition of a foreign key in the child table statement.
CONSTRAINT constraint_name FOREIGN KEY foreign_key_name (columns) REFERENCES parent_table(columns) ON DELETE action ON UPDATE action
Let's take a more detailed view of the above syntax:
CONSTRAINT
Clause allows you to define constraints for the foreign key constraint name. If it is omitted, MySQL automatically generates a name.FOREIGN KEY
Clause specifies the child table referenced parent table's primary key column column. You canFOREIGN KEY
place a foreign key name after clause, or allow MySQL to create a name for you. Please note, MySQL automatically creates aforeign_key_name
index name.REFERENCES
Reference clause specifies the parent table and the child table columns. InFOREIGN KEY
andREFERENCES
specified number of columns in the child and parent tables must be the same.ON DELETE
When the recording clause allows the definition of the parent table is deleted, the child table records how to perform operations. If omittedON DELETE
clause and delete records in the parent table, MySQL will refuse to delete the data associated with the child table. In addition, MySQL also provides some operation, so you can use other options, such as ON DELETE CASCADE , when you delete records in the parent table, MySQL can delete the child table records referenced in the parent table records. If you do not want to delete the child table records, please useON DELETE SET NULL
operation. When the record in the parent table is deleted, MySQL foreign key column values will be set to the sub-tableNULL
, with the proviso that the foreign key columns must accept the sub-tableNULL
values. Note that if you useON DELETE NO ACTION
orON DELETE RESTRICT
operation, MySQL will refuse to remove.ON UPDATE
When the clause allows you to specify a row in the parent table updates, sub-rows in the table will be how to perform operations. When the parent rows in the table is updated, can be omittedON UPDATE
clause MySQL refused to let any updates pairs of rows in the table.ON UPDATE CASCADE
Operation allows you to perform cross-table update, and when updating the parent table row,ON UPDATE SET NULL
the reset operation will be the value of the sub-rows in the table isNULL
the value.ON UPDATE NO ACTION
OrUPDATE RESTRICT
operate reject any updates.
Three, MySQL create a foreign key table example
dbdemo
database and two tables:
categories
and
products
. Each category has one or more products, each product belongs to a category.
products
Table
cat_id
field is defined as having
UPDATE ON CASCADE
and
DELETE ON RESTRICT
a foreign key.
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;
Fourth, add foreign key
Add a foreign key MySQL syntax
To a foreign key to an existing table, use the ALTER TABLE statement to define the syntax and the outer keys:
ALTER table_name ADD CONSTRAINT constraint_name FOREIGN KEY foreign_key_name(columns) REFERENCES parent_table(columns) ON DELETE action ON UPDATE action;
Add Foreign Key example MySQL
Now, we add a named vendors
new table, and change the products
table to include suppliers ID
fields:
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 products
add foreign key table, 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;
Now, the products
table has two foreign keys, one reference categories
table, the other is a reference vendors
table.
Fifth, delete MySQL foreign keys
ALTER TABLE
statement to a foreign key to delete, the following statement:
ALTER TABLE table_name DROP FOREIGN KEY constraint_name;
In the above statement:
- First, specify the name of the foreign key table is deleted from.
- Secondly, the name of the constraint placed
DROP FOREIGN KEY
after the clause.
Please note
constraint_name
that create or add the name constraints specified when the foreign key table. If you omit it, MySQL will generate a constraint name for you.
SHOW CREATE TABLE
statement as follows:
SHOW CREATE TABLE table_name;
For example, to view the products
list of foreign keys, use the following statement:
SHOW CREATE TABLE products;
The following is the output 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;
products
Table has two foreign key constraints: products_ibfk_1
and products_ibfk_2
.
You can use the following statement to delete products
table foreign keys:
ALTER TABLE products DROP FOREIGN KEY products_ibfk_1; ALTER TABLE products DROP FOREIGN KEY products_ibfk_2;
Six, MySQL disable foreign key checks
Sometimes, for some reason want to disable checking the foreign key (e.g. the data in the CSV file import table ) is very useful. If the check can not help with the foreign key, then the data must be loaded in the correct order, i.e. the data must first be loaded into the parent table, then the data loaded into the child table, which can be tedious. However, if the foreign key check is disabled, the data may be loaded in any order import.
Unless checked, otherwise you can not delete the table referenced by a foreign key constraint to disable foreign keys. When you delete a table, the table also deletes any constraint definitions.
To disable foreign key checks, use the following statement:
SET foreign_key_checks = 0;
Of course, you can enable it using the following statement:
SET foreign_key_checks = 1;
In this tutorial, we have introduced a lot of content about MySQL foreign key. Also introduces you to some very handy statements, MySQL allows you to effectively manage foreign keys.