Detailed explanation of the use of MySQL foreign keys

1. MySQL foreign key constraint syntax

MySQL supports foreign keys, which allow cross-referencing of related data between tables and help maintain the consistency of related data.

A foreign key relationship involves a parent table, which holds the initial column value, and a child table, whose column values ​​reference the column values ​​of the parent table. Foreign key constraints are defined on child tables.

The basic syntax for defining foreign key constraints consists of the following parts:

[CONSTRAINT [symbol]] FOREIGN KEY
    [index_name] (col_name, ...)
    REFERENCES tbl_name (col_name,...)
    [ON DELETE reference_option]
    [ON UPDATE reference_option]

where reference_optioncan be: RESTRICT | CASCADE | SET NULL | NO ACTION | SET DEFAULT

2. Identifier

The identifier is the name of the foreign key constraint. The naming of foreign key constraints follows the following rules:

  • If the CONSTRAINT symbol clause is defined, the symbol value is used.
  • If the CONSTRAINT symbol clause is not defined, or if a symbol value is not included after the CONSTRAINT keyword, the constraint name is automatically generated.
  • In MySQL 8.0.16 and later, the InnoDB and NDB storage engines ignore FOREIGN_KEY index_name if the CONSTRAINT symbol clause is not defined or if a symbol is not included after the CONSTRAINT keyword.
  • If a CONSTRAINT symbol value is defined, it must be unique in the database. Duplicate symbols produce an error similar to: ERROR 1005 (HY000): Can't create table 'test.fk1' (errno: 121).

3. Conditions and restrictions

Foreign key constraints are subject to the following conditions and restrictions:

  • The parent table and child table must use the same storage engine and cannot be defined as temporary tables.
  • Creating foreign key constraints requires REFERENCES permission on the parent table.
  • The corresponding column in the foreign key and the referenced key must have similar data types. Fixed-precision types such as INTEGER and DECIMAL must be the same size and sign. String types do not have to be the same length. For non-binary (character) string columns, the character set and collation must be the same.
  • MySQL supports foreign key references between one column and another column in a table (a column cannot have a foreign key reference to itself). In these cases, "child table record" refers to the dependent record in the same table.
  • MySQL requires indexes to be created on foreign and reference keys so that foreign key checks can be completed quickly and do not require table scans. In the referencing table, there must be an index in which the foreign key columns are listed as the first column in the same order. If such an index does not exist, it is automatically created on the referencing table. If you later create another index that can be used to enforce foreign key constraints, this index may be dropped silently. If index_name is given, it is used as described previously.

4. Reference operation

When an update or delete operation affects a key value in the parent table that has a matching row in the child table, the results depend on the referencing operations specified in the ON UPDATE and ON DELETE clauses of the FOREIGN KEY clause. Reference operations include:

  • CASCADE: Delete or update rows from the parent table and automatically delete or update matching rows in the child table. Supports ON DELETE CASCADE and ON UPDATE CASCADE. Between two tables, do not define several ON UPDATE CASCADE clauses that operate on the same column in the parent or child table.
  • SET NULL: Delete or update a row from the parent table and set the foreign key column or columns in the child table to NULL. Supports ON DELETE SET NULL and ON UPDATE SET NULL clauses.
  • RESTRICT: Reject delete or update operations on the parent table. Specifying RESTRICT (or NO ACTION) is the same as omitting the ON DELETE or ON UPDATE clause.
  • NO ACTION: keyword from standard SQL. For InnoDB, this is equivalent to RESTRICT; delete or update operations on the parent table are immediately rejected if the relevant foreign key value exists in the referenced table. NDB supports deferred checking, NO ACTION specifies deferred checking; when this option is used, constraint checking is not performed until commit time. Note that for NDB tables, this causes all foreign key checks on the parent and child tables to be deferred.
  • SET DEFAULT: This operation is recognized by the MySQL parser, but both InnoDB and NDB reject the table definition with an ON DELETE SET DEFAULT or ON UPDATE SET DEFAULT clause.

5. Foreign key check

Starting with MySQL 8.0.16, you can use the FOREIGN_KEY_CHECKS configuration option to enable or disable foreign key constraint checking. When this option is set to 1 or not specified, MySQL will check foreign key constraints. When this option is set to 0, MySQL disables all foreign key constraint checking.

SET FOREIGN_KEY_CHECKS=0;

Using this option can greatly improve the data import speed for database tables that contain a large number of foreign key constraints.

6. Lock

When performing an update, delete, or insert operation involving a foreign key constraint, the InnoDB storage engine attempts to obtain the necessary row-level shared (S) locks. If these locks cannot be acquired immediately, InnoDB may create a lock wait situation.

7. Foreign key error

When operating tables involving foreign key constraints, you may encounter some common errors, such as:

  • ERROR 1005 (HY000): Can't create table '...' (errno: 150): MySQL cannot create the table because the foreign key constraint cannot be created correctly. This may be due to a data type mismatch or the key being referenced does not exist.
  • ERROR 1215 (HY000): Cannot add foreign key constraint: MySQL cannot add a foreign key constraint. It's also possible that the data types don't match or that the referenced key doesn't exist.
  • ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails: An attempt was made to insert or update a row, but the foreign key constraint failed. This usually means you are trying to insert a value that does not exist in the parent table.

Guess you like

Origin blog.csdn.net/jkzyx123/article/details/132627388