mysql Foreign Keys of Foreign Key introduces and creates foreign keys

  • 2020-06-07 05:26:34
  • OfStack

In MySQL, tables of the InnoDB engine type support foreign key constraints.
Conditions for foreign keys:
1. Both tables must be InnoDB tables, and MyISAM tables do not support foreign keys for the time being (it is said that later versions may support them, but at least they do not support them at present);
2. Foreign key columns must be indexed. In the versions after MySQL 4.1.2, indexes are automatically created when foreign keys are created.
3. The columns of the two tables in the foreign key relationship must have similar data types, that is, the columns that can be converted to each other. For example, int and tinyint can, while int and char cannot.

Advantages of foreign keys: can make two tables associated, to ensure the data of 1 and achieve 1 some cascade operations;

Foreign key definition syntax:


[CONSTRAINT symbol] FOREIGN KEY [id] (index_col_name,  ... )
REFERENCES tbl_name (index_col_name,  ... )
[ON DELETE {RESTRICT | CASCADE | SET NULL | NO ACTION | SET DEFAULT}]
[ON UPDATE {RESTRICT | CASCADE | SET NULL | NO ACTION | SET DEFAULT}]

This syntax can be used with CREATE TABLE and ALTER TABLE. If CONSTRAINT symbol is not specified, MYSQL automatically generates a name.
ON DELETE and ON UPDATE represent event trigger restrictions, and parameters can be set:
RESTRICT (Limits foreign key changes in appearance)
CASCADE (with foreign key changes)
SET NULL (null)
SET DEFAULT (set default)
NO ACTION (no action, default)


Related articles: