Introduction to MySQL foreign key
A foreign key is a field in a table that matches a 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 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 has not only one column but also 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 can have 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 table is the same table. 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.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 statements or a DELETE JOIN statement.The same as deletion, you can also define a cascade on update action for the
customerNumber
foreign key to perform 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.
MySQL create table foreign key
MySQL create foreign key syntax
The following syntax illustrates how to define a foreign key in a child table in CREATE TABLE statement.- 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 refer to primary key columns in the parent table. You can put a foreign key name afterFOREIGN KEY
clause or leave it to let MySQL to create a name for you. Notice that MySQL automatically creates an index with theforeign_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 child table and parent table specified in theFOREIGN KEY
andREFERENCES
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 theON 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 lets MySQL to delete records in the child table that refer 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 theON DELETE SET NULL
action instead. MySQL will set the foreign key column values in the child table toNULL
when the record in the parent table is deleted, with a condition that the foreign key column in the child table must acceptNULL
values. Notice that if you useON DELETE NO ACTION
orON 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 theON UPDATE
clause to let MySQL to reject any update to the rows in the child table when the rows in the parent table are updated. TheON UPDATE CASCADE
action allows you to perform cross-table update, and theON UPDATE SET NULL
action resets the values in the rows in the child table toNULL
values when the rows in the parent table are updated. TheON UPDATE NO ACTION
orUPDATE RESTRICT
actions reject any updates.
MySQL create table foreign key example
The following example creates adbdemo
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.MySQL add foreign key
MySQL add 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:MySQL add foreign key example
Now, let’s add a new table namedvendors
and change the products
table to include the vendor id field:products
table, you use the following statement:products
table has two foreign keys, one refers to the categories
table and another refers to the vendors
table.MySQL drop foreign key
You also use theALTER TABLE
statement to drop foreign key as the following statement:- 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.
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:products
table, you use the following statement: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:MySQL disable foreign key checks
Sometimes, it is very useful to disable foreign key checks e.g., when you load data into the tables that have foreign keys. 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 into 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:
SOURCE : http://www.mysqltutorial.org/mysql-foreign-key/
0 komentar:
Posting Komentar