The setting and function of MySQL foreign key

Source: Internet
Author: User
Tags contains key mysql reference table name

The role of foreign keys:

Maintain data consistency and integrity, primarily to control the storage of data in foreign key tables. Causes the two tables to be associated, the foreign key can only reference the values of the columns in the outside!

For example:

A B two tables

A table contains the customer number, customer name

Table B contains orders for each customer

After the foreign key is available

You can only delete customer x in table A if you are sure that there are no customer x orders in table B

The prerequisite for establishing a foreign key is that the column in this table must be the same as the foreign key type (the foreign key must be the outer primary key).

Specify PRIMARY KEY Keywords: foreign key (column name)

Referencing foreign key keywords: references < foreign key table name > (foreign key column name)

Event Trigger restrictions: On delete and on update, to set parameter cascade (following foreign key changes), restrict (Restrict foreign key changes in the surface), set NULL (set NULL value), set default (set default), [Default]no action

For example:

Outtable table primary key ID type int

To create a table containing foreign keys:

CREATE TABLE Temp (

ID int,

Name Char (20),

FOREIGN key (ID) references outtable (ID) on DELETE cascade on UPDATE cascade);

Description: Set the ID column as a foreign key reference to the outer outtable ID column when the value of the foreign key deletes the corresponding column in this table screen except when the value of the foreign key changes the corresponding column value in this table.




Related Article

Alibaba Cloud 10 Year Anniversary

With You, We are Shaping a Digital World, 2009-2019

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.