1.7.3.2 FOREIGN KEY Constraints约束

Foreign keys let you cross-reference related data across tables, and foreign key constraints help keep this spread-out data consistent.外键允许跨表交叉引用相关数据,外键约束有助于保持这些分布数据的一致性。

MySQL supports ON UPDATE and ON DELETE foreign key references in CREATE TABLE and ALTER TABLE statements. MySQL支持CREATE TABLEALTER TABLE语句中的ON UPDATEON DELETE外键引用。The available referential actions are RESTRICT, CASCADE, SET NULL, and NO ACTION (the default).可用的引用操作有RESTRICTCASCADESET NULLNO ACTION(默认值)。

SET DEFAULT is also supported by the MySQL Server but is currently rejected as invalid by InnoDB. SET DEFAULT也受到MySQL Server的支持,但目前被InnoDB视为无效而拒绝。Since MySQL does not support deferred constraint checking, NO ACTION is treated as RESTRICT. 由于MySQL不支持延迟约束检查,因此NO ACTION被视为RESTRICTFor the exact syntax supported by MySQL for foreign keys, see Section 13.1.20.5, “FOREIGN KEY Constraints”.有关MySQL支持的外键的确切语法,请参阅第13.1.20.5节,“FOREIGN KEY约束”

MATCH FULL, MATCH PARTIAL, and MATCH SIMPLE are allowed, but their use should be avoided, as they cause the MySQL Server to ignore any ON DELETE or ON UPDATE clause used in the same statement. 允许使用MATCH FULLMATCH PARTIALMATCH SIMPLE,但应避免使用它们,因为它们会导致MySQL Server忽略同一语句中使用的任何ON DELETEON UPDATE子句。MATCH options do not have any other effect in MySQL, which in effect enforces MATCH SIMPLE semantics full-time.MATCH选项在MySQL中没有任何其他效果,它实际上全职强制执行MATCH SIMPLE语义。

MySQL requires that foreign key columns be indexed; if you create a table with a foreign key constraint but no index on a given column, an index is created.MySQL要求对外键列进行索引;如果创建的表具有外键约束,但对给定列没有索引,则会创建索引。

You can obtain information about foreign keys from the INFORMATION_SCHEMA.KEY_COLUMN_USAGE table. 可以从INFORMATION_SCHEMA.KEY_COLUMN_USAGE表中获取有关外键的信息。An example of a query against this table is shown here:此处显示了针对该表的查询示例:

mysql> SELECT TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME, CONSTRAINT_NAME
     > FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
     > WHERE REFERENCED_TABLE_SCHEMA IS NOT NULL;
+--------------+---------------+-------------+-----------------+
| TABLE_SCHEMA | TABLE_NAME    | COLUMN_NAME | CONSTRAINT_NAME |
+--------------+---------------+-------------+-----------------+
| fk1          | myuser        | myuser_id   | f               |
| fk1          | product_order | customer_id | f2              |
| fk1          | product_order | product_id  | f1              |
+--------------+---------------+-------------+-----------------+
3 rows in set (0.01 sec)

Information about foreign keys on InnoDB tables can also be found in the INNODB_FOREIGN and INNODB_FOREIGN_COLS tables, in the INFORMATION_SCHEMA database.关于InnoDB表上外键的信息也可以在INFORMATION_SCHEMA数据库的INNODB_FOREIGN表和INNODB_FOREIGN_COLS表中找到。

InnoDB and NDB tables support foreign keys.InnoDBNDB表支持外键。