[引]MySQL INNODB类型表的外键关联设置

本文详细介绍了MySQL中InnoDB引擎对外键约束的支持情况,包括简单的单列外键约束及复杂的多列外键约束示例,并阐述了各种操作如级联删除、设置为空等在不同场景下的行为。

Here is a simple example that relates parent and child tables through a single-column foreign key:

CREATE TABLE parent (id INT NOT NULL,
PRIMARY KEY (id)
) ENGINE=INNODB;
CREATE TABLE child (id INT, parent_id INT,
INDEX par_ind (parent_id),
FOREIGN KEY (parent_id) REFERENCES parent(id)
ON DELETE CASCADE
) ENGINE=INNODB;

A more complex example in which a product_order table has foreign keys for two other tables.
One foreign key references a two-column index in the product table.
The other references a single-column index in the customer table:

CREATE TABLE product (category INT NOT NULL, id INT NOT NULL,
price DECIMAL,
PRIMARY KEY(category, id)) ENGINE=INNODB;
CREATE TABLE customer (id INT NOT NULL,
PRIMARY KEY (id)) ENGINE=INNODB;
CREATE TABLE product_order (no INT NOT NULL AUTO_INCREMENT,
product_category INT NOT NULL,
product_id INT NOT NULL,
customer_id INT NOT NULL,
PRIMARY KEY(no),
INDEX (product_category, product_id),
FOREIGN KEY (product_category, product_id)
REFERENCES product(category, id)
ON UPDATE CASCADE ON DELETE RESTRICT,
INDEX (customer_id),
FOREIGN KEY (customer_id)
REFERENCES customer(id)) ENGINE=INNODB;


-----------

InnoDB also supports foreign key constraints. The syntax for a foreign key constraint definition in InnoDB looks like this:

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

Foreign keys definitions are subject to the following conditions:

  • Both tables must be InnoDB tables and they must not be TEMPORARY tables.

  • In the referencing table, there must be an index where the foreign key columns are listed as the first columns in the same order. Such an index is created on the referencing table automatically if it does not exist.

  • In the referenced table, there must be an index where the referenced columns are listed as the first columns in the same order.

  • Index prefixes on foreign key columns are not supported. One consequence of this is that BLOB and TEXT columns cannot be included in a foreign key, because indexes on those columns must always include a prefix length.

  • If the CONSTRAINT symbol clause is given, the symbol value must be unique in the database. If the clause is not given, InnoDB creates the name automatically.

InnoDB rejects any INSERT or UPDATE operation that attempts to create a foreign key value in a child table if there is no a matching candidate key value in the parent table. The action InnoDB takes for any UPDATE or DELETE operation that attempts to update or delete a candidate key value in the parent table that has some matching rows in the child table is dependent on the referential action specified using ON UPDATE and ON DELETE subclauses of the FOREIGN KEY clause. When the user attempts to delete or update a row from a parent table, and there are one or more matching rows in the child table, InnoDB supports five options regarding the action to be taken:

  • CASCADE: Delete or update the row from the parent table and automatically delete or update the matching rows in the child table. Both ON DELETE CASCADE and ON UPDATE CASCADE are supported. Between two tables, you should not define several ON UPDATE CASCADE clauses that act on the same column in the parent table or in the child table.

  • SET NULL: Delete or update the row from the parent table and set the foreign key column or columns in the child table to NULL. This is valid only if the foreign key columns do not have the NOT NULL qualifier specified. Both ON DELETE SET NULL and ON UPDATE SET NULL clauses are supported.

  • NO ACTION: In standard SQL, NO ACTION means no action in the sense that an attempt to delete or update a primary key value is not allowed to proceed if there is a related foreign key value in the referenced table. InnoDB rejects the delete or update operation for the parent table.

  • RESTRICT: Rejects the delete or update operation for the parent table. NO ACTION and RESTRICT are the same as omitting the ON DELETE or ON UPDATE clause. (Some database systems have deferred checks, and NO ACTION is a deferred check. In MySQL, foreign key constraints are checked immediately, so NO ACTION and RESTRICT are the same.)

  • SET DEFAULT: This action is recognized by the parser, but InnoDB rejects table definitions containing ON DELETE SET DEFAULT or ON UPDATE SET DEFAULT clauses.

Note that InnoDB supports foreign key references within a table. In these cases, “child table records” really refers to dependent records within the same table.

InnoDB requires indexes on foreign keys and referenced keys so that foreign key checks can be fast and not require a table scan. The index on the foreign key is created automatically. This is in contrast to some older versions, in which indexes had to be created explicitly or the creation of foreign key constraints would fail.

Corresponding columns in the foreign key and the referenced key must have similar internal data types inside InnoDB so that they can be compared without a type conversion. The size and sign of integer types must be the same. The length of string types need not be the same. If you specify a SET NULL action, make sure that you have not declared the columns in the child table as NOT NULL.

If MySQL reports an error number 1005 from a CREATE TABLE statement, and the error message refers to errno 150, table creation failed because a foreign key constraint was not correctly formed. Similarly, if an ALTER TABLE fails and it refers to errno 150, that means a foreign key definition would be incorrectly formed for the altered table. You can use SHOW ENGINE INNODB STATUS to display a detailed explanation of the most recent InnoDB foreign key error in the server.

Note: InnoDB does not check foreign key constraints on those foreign key or referenced key values that contain a NULL column.

Note: Currently, triggers are not activated by cascaded foreign key actions.

You cannot create a table with a column name that matches the name of an internal InnoDB column (including DB_ROW_ID, DB_TRX_ID, DB_ROLL_PTR and DB_MIX_ID). In versions of MySQL before 5.1.10 this would cause a crash, since 5.1.10 the server will report error 1005 and refers to errno -1 in the error message.

Deviation from SQL standards: If there are several rows in the parent table that have the same referenced key value, InnoDB acts in foreign key checks as if the other parent rows with the same key value do not exist. For example, if you have defined a RESTRICT type constraint, and there is a child row with several parent rows, InnoDB does not allow the deletion of any of those parent rows.

InnoDB performs cascading operations through a depth-first algorithm, based on records in the indexes corresponding to the foreign key constraints.

Deviation from SQL standards: A FOREIGN KEY constraint that references a non-UNIQUE key is not standard SQL. It is an InnoDB extension to standard SQL.

Deviation from SQL standards: If ON UPDATE CASCADE or ON UPDATE SET NULL recurses to update the same table it has previously updated during the cascade, it acts like RESTRICT. This means that you cannot use self-referential ON UPDATE CASCADE or ON UPDATE SET NULL operations. This is to prevent infinite loops resulting from cascaded updates. A self-referential ON DELETE SET NULL, on the other hand, is possible, as is a self-referential ON DELETE CASCADE. Cascading operations may not be nested more than 15 levels deep.

Deviation from SQL standards: Like MySQL in general, in an SQL statement that inserts, deletes, or updates many rows, InnoDB checks UNIQUE and FOREIGN KEY constraints row-by-row. According to the SQL standard, the default behavior should be deferred checking. That is, constraints are only checked after the entire SQL statement has been processed. Until InnoDB implements deferred constraint checking, some things will be impossible, such as deleting a record that refers to itself via a foreign key.

<think> 首先,用户的问题是关于MySQL的:他们想查找MySQL中“条件关联”和“组关联”的相关语句。我需要基于提供的用来回答这个问题。 回顾用: - 用[1]提到了、内连接、连接、关联子查询。 - 用[2]讨论了是否必要,并给出了连接查询的SQL示例(内连接、左连接、右连接)。 - 用[3]涉及约束的操作,包括删除设置擎。 - 用[4]展示了内连接查询的示例。 - 用[5]提供了创建约束的语法。 用户提到了“条件关联”和“组关联”。在标准SQL术语中: - “条件关联”可能指的是带条件的连接查询(如使用WHERE子句)。 - “组关联”听起来像是一个误译或特定术语。可能指的是约束(foreign key constraints)或涉及关联。 从用看: - 用[2]有连接查询的语句(内连接、左连接、右连接),这些可以包含条件。 - 用[1]和[2]讨论了关联子查询。 用户的问题:“MySQL条件关联和组关联的语句”。可能: - “条件关联” → 带条件的连接查询。 - “组关联” → 可能指约束或分组查询中的关联?但“组”可能是个打字错误或指“分组(group)”,但通常是约束。 在用[4]中有一个示例:`SELECT role.role_name FROM hero INNER JOIN role WHERE hero.age >= 29 AND role.role_id=hero.role_id`,这显示了一个带条件的内连接(条件关联)。 对于“组关联”,可能是指创建或使用约束的语句。用[2]和[5]提供了创建约束的语法。用[5]:`constraint FK_id foreign key(dept_id) references student(id)`。 所以,我需要在回答中覆盖: 1. 条件关联:带条件的连接查询(如使用ON或WHERE子句)。 2. 关联:创建约束的语句。 用户要求“生成相关问题”,所以我需要在最后添加相关问题。 回答结构: - 使用中文回答。 - 结构清晰,逐步解释。 - 应用用,在末尾添加用标识。 - 对于数学表达式,用户提到行内使用$...$,但这里是SQL,不需要LaTeX数学,除非有数学部分。可能SQL语句本身就是需要格式化的代码。 - 用户说“所有行内数学表达式...”,但这里是SQL语句,所以我会用代码块来处理SQL代码,类似于示例中的Python代码块。 步骤: 1. 解释条件关联,并提供SQL示例。 2. 解释关联(假设“组关联”指约束),并提供创建语句。 3. 基于用添加用标识。 4. 在最后生成相关问题。 从用中提取信息: - 对于连接查询:用[2]有`SELECT 字段名 FROM 表名 AS a JOIN 表名 AS b ON (a.字段名称=b.字段名称);` 等。 - 用[4]有带条件的例子。 - 对于用[2]和[5]有创建语法。 生成相关问题: - 相关问题应基于主题,如“如何优化条件关联的性能?”或“约束的优缺点?”。 最终回答大纲: - 介绍主题。 - 解释并举例条件关联。 - 解释并举例关联。 - 添加用标识。 - 生成相关问题。 </think>### MySQL条件关联关联语句详解 在MySQL中,"条件关联"通常指在连接查询(如内连接、左连接)中加入额条件的语句,而"关联"指通过约束(FOREIGN KEY)实现的表间关系管理。以下是基于MySQL标准语法的详细说明和示例,参考了相关技术文档[^1][^2][^3][^4][^5]。 #### 1. **条件关联语句** 条件关联通过在连接查询的`ON`或`WHERE`子句中添加额条件实现。常用语法包括: - **内连接(INNER JOIN)**:结合`WHERE`子句过滤数据。 ```sql SELECT a.字段, b.字段 FROM 表A AS a INNER JOIN 表B AS b ON a.关联字段 = b.关联字段 WHERE 额条件; -- 条件关联部分 ``` **示例**:查询年龄≥29的英雄及其角色名(带条件关联)[^4]: ```sql SELECT role.role_name FROM hero INNER JOIN role ON hero.role_id = role.role_id -- 基础关联 WHERE hero.age >= 29; -- 条件关联 ``` - **左连接/右连接(LEFT/RIGHT JOIN)**:使用`ON`子句嵌入条件。 ```sql SELECT a.字段, b.字段 FROM 表A AS a LEFT JOIN 表B AS b ON a.关联字段 = b.关联字段 AND 额条件; -- 条件直接嵌入ON ``` **示例**:左连接查询部门信息,仅关联有效员工: ```sql SELECT dept.name, emp.name FROM departments AS dept LEFT JOIN employees AS emp ON dept.id = emp.dept_id AND emp.status = 'active'; ``` #### 2. **关联语句** 关联通过`FOREIGN KEY`约束定义表间关系,确保数据完整性。语法包括: - **创建约束**: ```sql CREATE TABLE 从表 ( 字段 类型, CONSTRAINT 约束名 FOREIGN KEY (字段) REFERENCES 主表 (主字段) ON DELETE 操作 -- 如CASCADE(级联删除)、SET NULL(设为空) ON UPDATE 操作 -- 如RESTRICT(限制更新) ); ``` **示例**:在`employees`表中添加关联到`departments`表[^5]: ```sql CREATE TABLE employees ( id INT PRIMARY KEY, dept_id INT, CONSTRAINT fk_dept FOREIGN KEY (dept_id) REFERENCES departments(id) ON DELETE CASCADE -- 级联删除 ); ``` - **修改或删除**: ```sql -- 添加(表已存在) ALTER TABLE 从表 ADD CONSTRAINT 约束名 FOREIGN KEY (字段) REFERENCES 主表 (主字段); -- 删除 ALTER TABLE 表名 DROP FOREIGN KEY 约束名; -- 需先查询约束名[^3] ``` **注意**:功能需确保表擎为InnoDB(默认MyISAM不支持),可在`my.ini`配置`default-storage-engine=INNODB`[^3]。 #### 关区别 - **条件关联**:用于查询时动态过滤数据,不改变表结构。 - **关联**:用于定义数据完整性规则,是表设计的一部分。 实际应用中,**非强制**,但能防止无效关联;**条件关联**则灵活支持复杂查询[^2][^4]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值