Detailed mysql foreign keys

First, the foreign key Introduction

Field represents a foreign key in the table is a reference to a field in another table. Resulting in the limitation of the foreign key in the dependent table data, so MySQL can maintain referential integrity.

Let's look at the sample database (yiibaidb) the following two database tables: customersthe ER and `orders`` of FIG.

The figure above there are two tables: customersand orders. Each customer zero or more orders, each order belongs to a customer. customersTables and ordersrelationships between tables are many, and it is customerNumberspecified in the field ordersto establish a foreign key table (reference customerstable customerNumberfields). ordersTable customerNumberfields customerstable customerNumberassociated primary key field.

customersTable called the parent table or the referenced table, ordersthe table is called the child table or the referenced table.

Table can have multiple foreign keys, each foreign key in the child table may refer to a different parent table.

Child table row must contain a value present in the parent table, for example, orderseach order record in the table must customersexist in the table customerNumber. Therefore, multiple orders can refer to the same customers, so this relationship is called a (client) to many (orders) or one to many.

Sometimes, the child and parent tables are the same, a foreign key to return to the table's primary key.

reportToA reference column is employeeNumbera foreign key column, employeeNumberthe column is employeesthe primary key for the table to reflect the reporting structure between employees, i.e. employees and each employee reports sent to other employees can have zero or more direct reports. For information about how to use there, please refer to the self-ligation tutorials to help you to query data query based on this table.

reportToAlso referred to as a recursive foreign key or foreign key from the referenced.

Foreign key implementation of referential integrity, can help you automatically maintain the consistency and integrity of data. For example, you can not create orders for customers that do not exist.

Additionally, you can customerNumberdelete the foreign key to cascade, so that customerswhen you delete the customer, all orders associated with the client will also be deleted table. This saves you use multiple DELETE statements , or DELETE JOIN statements time and effort.

And remove the same, may also be a customerNumberforeign key definitions cascade update operations to perform cross-table update, without the use of a plurality UPDATE statement or UPDATE the JOIN statement.

In MySQL, InnoDB storage engines support foreign keys, so you must create the InnoDB table to use foreign key constraints.

Second, create a foreign key

MySQL create a foreign key syntax

The following syntax shows how the CREATE TABLE definition of a foreign key in the child table statement.

CONSTRAINT constraint_name
FOREIGN KEY foreign_key_name (columns)
REFERENCES parent_table(columns)
ON DELETE action
ON UPDATE action

 

Let's take a more detailed view of the above syntax:

  • CONSTRAINTClause allows you to define constraints for the foreign key constraint name. If it is omitted, MySQL automatically generates a name.
  • FOREIGN KEYClause specifies the child table referenced parent table's primary key column column. You can FOREIGN KEYplace a foreign key name after clause, or allow MySQL to create a name for you. Please note, MySQL automatically creates a foreign_key_nameindex name.
  • REFERENCESReference clause specifies the parent table and the child table columns. In FOREIGN KEYand REFERENCESspecified number of columns in the child and parent tables must be the same.
  • ON DELETEWhen the recording clause allows the definition of the parent table is deleted, the child table records how to perform operations. If omitted ON DELETEclause and delete records in the parent table, MySQL will refuse to delete the data associated with the child table. In addition, MySQL also provides some operation, so you can use other options, such as ON DELETE CASCADE , when you delete records in the parent table, MySQL can delete the child table records referenced in the parent table records. If you do not want to delete the child table records, please use ON DELETE SET NULLoperation. When the record in the parent table is deleted, MySQL foreign key column values will be set to the sub-table NULL, with the proviso that the foreign key columns must accept the sub-table NULLvalues. Note that if you use ON DELETE NO ACTIONor ON DELETE RESTRICToperation, MySQL will refuse to remove.
  • ON UPDATEWhen the clause allows you to specify a row in the parent table updates, sub-rows in the table will be how to perform operations. When the parent rows in the table is updated, can be omitted ON UPDATEclause MySQL refused to let any updates pairs of rows in the table. ON UPDATE CASCADEOperation allows you to perform cross-table update, and when updating the parent table row, ON UPDATE SET NULLthe reset operation will be the value of the sub-rows in the table is NULLthe value. ON UPDATE NO ACTIONOr UPDATE RESTRICToperate reject any updates.

Three, MySQL create a foreign key table example

The following example creates a dbdemo database and two tables: categories and products . Each category has one or more products, each product belongs to a category. products Table cat_id field is defined as having UPDATE ON CASCADE and DELETE ON RESTRICT a foreign key.
CREATE DATABASE IF NOT EXISTS dbdemo;

USE dbdemo;

CREATE TABLE categories(
   cat_id int not null auto_increment primary key,
   cat_name varchar(255) not null,
   cat_description text
) ENGINE=InnoDB;

CREATE TABLE products(
   prd_id int not null auto_increment primary key,
   prd_name varchar(355) not null,
   prd_price decimal,
   cat_id int not null,
   FOREIGN KEY fk_cat(cat_id)
   REFERENCES categories(cat_id)
   ON UPDATE CASCADE
   ON DELETE RESTRICT
)ENGINE=InnoDB;

Fourth, add foreign key

Add a foreign key MySQL syntax

To a foreign key to an existing table, use the ALTER TABLE statement to define the syntax and the outer keys:

ALTER table_name
ADD CONSTRAINT constraint_name
FOREIGN KEY foreign_key_name(columns)
REFERENCES parent_table(columns)
ON DELETE action
ON UPDATE action;

Add Foreign Key example MySQL

Now, we add a named vendorsnew table, and change the productstable to include suppliers IDfields:

USE dbdemo;

CREATE TABLE vendors(
    vdr_id int not null auto_increment primary key,
    vdr_name varchar(255)
)ENGINE=InnoDB;

ALTER TABLE products 
ADD COLUMN vdr_id int not null AFTER cat_id;

To productsadd foreign key table, use the following statement:

ALTER TABLE products
ADD FOREIGN KEY fk_vendor(vdr_id)
REFERENCES vendors(vdr_id)
ON DELETE NO ACTION
ON UPDATE CASCADE;

Now, the productstable has two foreign keys, one reference categoriestable, the other is a reference vendorstable.

Fifth, delete MySQL foreign keys

You can also use the ALTER TABLE statement to a foreign key to delete, the following statement:
ALTER TABLE table_name 
DROP FOREIGN KEY constraint_name;

In the above statement:

  • First, specify the name of the foreign key table is deleted from.
  • Secondly, the name of the constraint placed DROP FOREIGN KEYafter the clause.
Please note constraint_name that create or add the name constraints specified when the foreign key table. If you omit it, MySQL will generate a constraint name for you.
Generated constraint name of the table to acquire, use the SHOW CREATE TABLE statement as follows:
SHOW CREATE TABLE table_name;

For example, to view the productslist of foreign keys, use the following statement:

SHOW CREATE TABLE products;

The following is the output statement:

CREATE TABLE products (
  prd_id int(11) NOT NULL AUTO_INCREMENT,
  prd_name varchar(355) NOT NULL,
  prd_price decimal(10,0) DEFAULT NULL,
  cat_id int(11) NOT NULL,
  vdr_id int(11) NOT NULL,
  PRIMARY KEY (prd_id),
  KEY fk_cat (cat_id),
  KEY fk_vendor(vdr_id),

  CONSTRAINT products_ibfk_2 
  FOREIGN KEY (vdr_id) 
  REFERENCES vendors (vdr_id) 
  ON DELETE NO ACTION 
  ON UPDATE CASCADE,

  CONSTRAINT products_ibfk_1 
  FOREIGN KEY (cat_id) 
  REFERENCES categories (cat_id) 
  ON UPDATE CASCADE
) ENGINE=InnoDB;

productsTable has two foreign key constraints: products_ibfk_1and products_ibfk_2.

You can use the following statement to delete productstable foreign keys:

ALTER  TABLE products 
 DROP  FOREIGN  KEY products_ibfk_1; 

ALTER  TABLE products 
 DROP  FOREIGN  KEY products_ibfk_2;

Six, MySQL disable foreign key checks

Sometimes, for some reason want to disable checking the foreign key (e.g. the data in the CSV file import table ) is very useful. If the check can not help with the foreign key, then the data must be loaded in the correct order, i.e. the data must first be loaded into the parent table, then the data loaded into the child table, which can be tedious. However, if the foreign key check is disabled, the data may be loaded in any order import.

Unless checked, otherwise you can not delete the table referenced by a foreign key constraint to disable foreign keys. When you delete a table, the table also deletes any constraint definitions.

To disable foreign key checks, use the following statement:

SET foreign_key_checks = 0;

Of course, you can enable it using the following statement:

SET foreign_key_checks = 1;

In this tutorial, we have introduced a lot of content about MySQL foreign key. Also introduces you to some very handy statements, MySQL allows you to effectively manage foreign keys.







 



Guess you like

Origin www.cnblogs.com/tkzc2013/p/11454583.html