`
liujianguangaaa
  • 浏览: 236996 次
  • 性别: Icon_minigender_1
  • 来自: 湖南
社区版块
存档分类
最新评论

FOREIGN KEY Constraints

阅读更多

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

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

reference_option:
    RESTRICT | CASCADE | SET NULL | NO ACTION

index_name represents a foreign key ID. If given, this is ignored if an index for the foreign key is defined explicitly. Otherwise, if InnoDB creates an index for the foreign key, it uses index_name for the index name.

Foreign keys definitions are subject to the following conditions:

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

  • Corresponding columns in the foreign key and the referenced key must have similar internal data types insideInnoDB 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. For nonbinary (character) string columns, the character set and collation must be the same.

  • InnoDB requires indexes on foreign keys and referenced keys so that foreign key checks can be fast and not require a table scan. 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. (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.) index_name, if given, is used as described previously.

  • InnoDB permits a foreign key to reference any index column or group of columns. However, 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. When an UPDATE or DELETE operation affects a key value in the parent table that has matching rows in the child table, the result depends on the referential actionspecified using ON UPDATE and ON DELETE subclauses of the FOREIGN KEY clause. InnoDB supports five options regarding the action to be taken. If ON DELETE or ON UPDATE are not specified, the default action is RESTRICT.

  • 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, do not define several ON UPDATE CASCADE clauses that act on the same column in the parent table or in the child table.

    Note

    Currently, cascaded foreign key actions do not activate triggers.

  • 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. Both ON DELETE SET NULL and ON UPDATE SET NULL clauses are supported.

    If you specify a SET NULL action, make sure that you have not declared the columns in the child table as NOT NULL.

  • RESTRICT: Rejects the delete or update operation for the parent table. Specifying RESTRICT (or NO ACTION) is the same as omitting the ON DELETE or ON UPDATE clause.

  • NO ACTION: A keyword from standard SQL. In MySQL, equivalent to RESTRICTInnoDB rejects the delete or update operation for the parent table if there is a related foreign key value in the referenced table. Some database systems have deferred checks, and NO ACTION is a deferred check. In MySQL, foreign key constraints are checked immediately, so NO ACTION is the same as RESTRICT.

  • 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.

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

Examples of Foreign Key Clauses

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 customertable:

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 enables you to add a new foreign key constraint to a table by using ALTER TABLE:

ALTER TABLE tbl_name
    ADD [CONSTRAINT [symbol]] FOREIGN KEY
    [index_name] (index_col_name, ...)
    REFERENCES tbl_name (index_col_name,...)
    [ON DELETE reference_option]
    [ON UPDATE reference_option]

The foreign key can be self referential (referring to the same table). When you add a foreign key constraint to a table using ALTER TABLEremember to create the required indexes first.

Foreign Keys and ALTER TABLE

InnoDB supports the use of ALTER TABLE to drop foreign keys:

ALTER TABLE tbl_name DROP FOREIGN KEY fk_symbol;

If the FOREIGN KEY clause included a CONSTRAINT name when you created the foreign key, you can refer to that name to drop the foreign key. Otherwise, the fk_symbol value is internally generated by InnoDB when the foreign key is created. To find out the symbol value when you want to drop a foreign key, use the SHOW CREATE TABLE statement. For example:

mysql> SHOW CREATE TABLE ibtest11c\G
*************************** 1. row ***************************
       Table: ibtest11c
Create Table: CREATE TABLE `ibtest11c` (
  `A` int(11) NOT NULL auto_increment,
  `D` int(11) NOT NULL default '0',
  `B` varchar(200) NOT NULL default '',
  `C` varchar(175) default NULL,
  PRIMARY KEY  (`A`,`D`,`B`),
  KEY `B` (`B`,`C`),
  KEY `C` (`C`),
  CONSTRAINT `0_38775` FOREIGN KEY (`A`, `D`)
REFERENCES `ibtest11a` (`A`, `D`)
ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `0_38776` FOREIGN KEY (`B`, `C`)
REFERENCES `ibtest11a` (`B`, `C`)
ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=INNODB CHARSET=latin1
1 row in set (0.01 sec)

mysql> ALTER TABLE ibtest11c DROP FOREIGN KEY `0_38775`;

You cannot add a foreign key and drop a foreign key in separate clauses of a single ALTER TABLE statement. Separate statements are required.

If ALTER TABLE for an InnoDB table results in changes to column values (for example, because a column is truncated), InnoDB's FOREIGN KEY constraint checks do not notice possible violations caused by changing the values.

How Foreign Keys Work with Other MySQL Command

The InnoDB parser permits table and column identifiers in a FOREIGN KEY ... REFERENCES ... clause to be quoted within backticks. (Alternatively, double quotation marks can be used if the ANSI_QUOTES SQL mode is enabled.) The InnoDB parser also takes into account the setting of the lower_case_table_names system variable.

InnoDB returns a table's foreign key definitions as part of the output of the SHOW CREATE TABLE statement:

SHOW CREATE TABLE tbl_name;

mysqldump also produces correct definitions of tables in the dump file, and does not forget about the foreign keys.

To make it easier to reload dump files for tables that have foreign key relationships, mysqldump automatically includes a statement in the dump output to set foreign_key_checks to 0. This avoids problems with tables having to be reloaded in a particular order when the dump is reloaded. It is also possible to set this variable manually:

mysql> SET foreign_key_checks = 0;
mysql> SOURCE dump_file_name;
mysql> SET foreign_key_checks = 1;

This enables you to import the tables in any order if the dump file contains tables that are not correctly ordered for foreign keys. It also speeds up the import operation. Setting foreign_key_checks to 0 can also be useful for ignoring foreign key constraints during LOAD DATA and ALTER TABLE operations. However, even ifforeign_key_checks = 0, InnoDB does not permit the creation of a foreign key constraint where a column references a nonmatching column type. Also, if an InnoDB table has foreign key constraints, ALTER TABLE cannot be used to change the table to use another storage engine. To alter the storage engine, drop any foreign key constraints first.

InnoDB does not permit you to drop a table that is referenced by a FOREIGN KEY constraint, unless you do SET foreign_key_checks = 0. When you drop a table, the constraints that were defined in its create statement are also dropped.

If you re-create a table that was dropped, it must have a definition that conforms to the foreign key constraints referencing it. It must have the right column names and types, and it must have indexes on the referenced keys, as stated earlier. If these are not satisfied, MySQL returns error number 1005 and refers to error 150 in the error message.

If MySQL reports an error number 1005 from a font

评论

相关推荐

    bbs论坛项目运用SSH框架Oracle数据库编写的一个简单示列项目

    -- Create/Recreate primary, unique and foreign key constraints alter table USERS add constraint PK_USERID primary key (USERID) using index tablespace SYSTEM pctfree 10 initrans 2 maxtrans 255 ...

    xtree java 异步 树 demo

    xtree java异步加载树demo 环境:myeclipse6.5+jdk1.5+tomcat5.5+...-- Create/Recreate primary, unique and foreign key constraints alter table APPMENU add constraint PK_APPMENU primary key (APPMENUID);

    InnoDB 中文参考手册

    MySQL 的企业级解决方案,高实用性以及强健的数据完整性 MySQL 事务,行级锁定,热备份以及外键支持 - - 无需损失 MySQL 的高速性能 ...InnoDB 是 MySQL 上第一个提供外键约束(FOREIGN KEY constraints)的表引擎。

    InnoDB中文参考手册

    InnoDB 是 MySQL 上第一个提供外键约束(FOREIGN KEY constraints)的表引擎。 InnoDB 的设计目标是处理大容量数据库系统,它的 CPU 利用率是其它基于磁盘的关系数据库引擎所不能比的。 在技术上,InnoDB 是一套放在...

    ORACLE的索引和约束详解.pdf

    **外键约束(Foreign Key Constraints)** 外键约束保证了数据的一致性和参照完整性,它定义了一个字段或一组字段与另一个表的主键或唯一键之间的关系。外键字段只能包含被引用表的引用码或NULL值。外键约束可以是自...

    SQL的高级功能.pdf

    - 外键码约束(Foreign Key Constraints):确保数据的引用完整性,定义表间关系。 - 非空值约束(NOT NULL Constraints):确保字段不接受空值。 - CHECK约束:用于限制列的值必须满足的条件。 - 断言约束...

    SQLServer 高级篇

    7. **外键约束(FOREIGN KEY Constraints)**: - 外键约束确保一个表中的列引用另一个表中的主键。 - 示例: - **Persons 表**: ```sql CREATE TABLE Persons ( Id_P int NOT NULL PRIMARY KEY, LastName ...

    oracle_OCP-051答案解析

    The NEW_SALES table would get created and all the FOREIGN KEY constraints defined on the specified columns would be passed to the new table.** - **解析:** 错误。当使用`CREATE TABLE AS SELECT`命令时...

    Devart LinqConnect 3.1

    The algorithm for forming the Navigation Properties names, when there are several FOREIGN KEY constraints between the same tables, is changed The documentation generation for navigation properties is ...

    图书馆管理系统

    此外,为了保证数据的一致性和完整性,可能还会设置一些约束,如外键约束(Foreign Key Constraints)来保证关联表之间的关系,唯一性约束(Unique Constraints)防止重复数据,以及检查约束(Check Constraints)...

    mysql中国省市县列表

    2. 关联查询:利用外键约束(Foreign Key Constraints)确保数据的一致性和完整性,通过省份ID和城市ID进行关联查询。 3. 数据更新:由于行政区划可能会发生变化,因此需要定期更新这些数据以保持准确性。 4. 性能...

    Advanced Rails Recipes

    Add ForeignKey Constraints** 介绍如何在数据库表之间建立外键约束,从而保证数据的一致性和完整性。 **9. Write Custom Validations** 讲解如何编写自定义验证规则,以满足更复杂的业务需求。 **10. Take ...

    图书管理系统 asp.net2.0 sql2005

    例如,使用外键约束(Foreign Key Constraints)来关联不同表之间的数据,保证数据的关联性。 4. Web服务:可能还会涉及到使用ASP.NET的Web服务(ASMX或WCF)来提供API接口,供外部应用调用,比如移动应用或其它...

    MySQL数据库应用案例视频教程下载第22讲 论坛管理系统数据库设计.zip

    同时,通过外键约束(Foreign Key Constraints)来维护数据的一致性和完整性,如帖子表中的主题ID和用户ID应与主题表和用户表的主键关联。 此外,还要考虑性能优化,比如使用索引(Indexes)加速查询,尤其是对经常...

    delphi7数据库应用开发

    同时,使用外键约束(Foreign Key Constraints)可以维护数据库间的关系,确保数据的一致性。 在进行数据库应用开发时,还需要关注性能优化。这包括合理设计数据库结构,避免全表扫描,以及使用存储过程和视图等...

    Laravel开发-laravel-schema .zip

    6. **Foreign Key Constraints** Laravel也支持外键约束,用于维护数据的一致性和完整性。例如,为`posts`表添加一个与`users`表关联的外键: ```php $table->foreignId('user_id')->constrained()->onDelete('...

    实用JPA开发指南----jpa核心技术(关联关系等的配置高级配置)

    3. **外键约束(Foreign Key Constraints)**: JPA支持声明外键约束,确保数据的一致性和完整性。通过`@JoinColumn`或`@JoinColumns`注解定义外键。 4. **复合主键(Composite Primary Keys)**: 当一个实体的主键...

    sql 数据库程序设计

    4. 外键约束(Foreign Key Constraints): 在数据库设计中,外键用于建立和维护两个表之间的联系。这里提到的外键如`FK_员工基本信息_属于_部门`表明`员工基本信息`表中的某个字段依赖于`部门`表的数据,确保每个员工...

    How Can I Make it Faster to Import Data into MySQL Server

    4. **外键检查(FOREIGN KEY constraints)**:对于含有外键约束的表,可以在导入期间暂时关闭外键检查,以便更快地完成导入。 5. **批量插入(Multiple Insert Statements)**:使用批量插入语句代替单条记录的...

    hibernate 映射-一对多双向

    9. **外键约束(Foreign Key Constraints)**:在数据库层面,一对多关联通常通过外键实现。Hibernate可以自动处理外键的创建和维护,也可以手动配置。 10. **关联的导航(Navigation)**:在Java代码中,通过...

Global site tag (gtag.js) - Google Analytics