Foreign keys let you cross-reference related data across tables, and foreign key constraints help keep this spread-out data consistent.外键允许跨表交叉引用相关数据,外键约束有助于保持这些分布数据的一致性。
MySQL supports MySQL支持ON UPDATE
and ON DELETE
foreign key references in CREATE TABLE
and ALTER TABLE
statements. CREATE TABLE
和ALTER TABLE
语句中的ON UPDATE
和ON DELETE
外键引用。The available referential actions are 可用的引用操作有RESTRICT
, CASCADE
, SET NULL
, and NO ACTION
(the default).RESTRICT
、CASCADE
、SET NULL
和NO 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, 由于MySQL不支持延迟约束检查,因此NO ACTION
is treated as RESTRICT
. NO ACTION
被视为RESTRICT
。For 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 FULL
、MATCH PARTIAL
和MATCH SIMPLE
,但应避免使用它们,因为它们会导致MySQL Server忽略同一语句中使用的任何ON DELETE
或ON 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.InnoDB
和NDB
表支持外键。