Detailed explanation of MySQL foreign key constraints

Detailed explanation of MySQL foreign key constraints

Official documentation:
https://dev.mysql.com/doc/refman/5.7/en/create-table-foreign-keys.html

1. Foreign key function:

MySQL uses foreign key constraints to ensure the integrity and accuracy of data between tables.

2. Conditions for using foreign keys

  • Both tables must be InnoDB tables. MyISAM tables do not support foreign keys for the time being (it is said that future versions may support it, but at least it is not supported at present)
  • The foreign key column must have an index created. MySQL 4.1.2 and later versions will automatically create an index when creating a foreign key, but if you use an earlier version, you need to create an index explicitly.
  • The columns of the two tables in the foreign key relationship must have similar data types, that is, columns that can be converted to each other, such as int and tinyint, but not int and char.

3. Create Grammar

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

reference_option:
RESTRICT | CASCADE | SET NULL | NO ACTION | SET DEFAULT

This syntax can be used in CREATE TABLE and ALTER TABLE. If you do not specify the CONSTRAINT symbol, MYSQL will automatically generate a name.
ON DELETE and ON UPDATE indicate event triggering restrictions, and you can set parameters:
RESTRICT (restrict changes to foreign keys in foreign tables)
CASCADE (follow foreign key changes)
SET NULL
SET DEFAULT (Set the default value)
NO ACTION (no action, default)

CASCADE: Indicates that when the parent table is updated or deleted, the corresponding records in the child table are updated or deleted.
RESTRICT and NO ACTION: When the child table has related records, the parent table cannot be deleted or updated independently.
SET NULL: Indicates that when the parent table is updated or deleted, the corresponding fields of the child table are set to NULL

4. Case Demonstration

CASCADE constraint mode

1. Create the power table (parent table) country
create table country (
id int not null,
name varchar(30),
primary key(id)
);

2. Insert records insert into country values(1,'Western Europe');
insert into country values(2,'Maya');
insert into country values(3,'Sicily');

3. Create a arms table (sub-table) and establish constraints create table solider (
id int not null,
name varchar(30),
country_id int,
primary key(id),
foreign key(country_id) references country(id) on delete cascade on update cascade,
);

4. Reference integrity test insert into solider values(1,'Western European trainee infantry',1);
#insert successfully insert into solider values(2,'Maya short spearman',2);
#insert successfully insert into solider values(3,'Sicily Norman Knights',3)
#insert successfullyinsert into solider values(4,'French Swordsman',4);
#Insert failed because there is no faction with id 4 in the country table. 5. Constraint method test insert into solider values(4, 'Maya Tiger Warriors', 2);
#Successfully inserted delete from country where id=2;
#This will cause the records with id 2 and 4 in the solider table to be deleted at the same time, because this faction no longer exists in the parent table, so the corresponding arms will naturally disappear update country set id=8 where id=1;
#As a result, all records in the solider table with country_id 1 will also be modified to 8

With SET NULL constraint

1. Create a soldier table (sub-table) and establish a constraint relationship drop table if exists solider;
create table solider(
id int not null,
name varchar(30),
country_id int,
primary key(id),
foreign key(country_id) references country(id) on delete set null on update set null,
);

2. Reference integrity test insert into solider values(1,'Western European trainee infantry',1);
#insert successfully insert into solider values(2,'Maya short spearman',2);
#insert successfully insert into solider values(3,'Sicily Norman Knights',3)
#insert successfullyinsert into solider values(4,'French Swordsman',4);
#Insert failed because there is no faction with id 4 in the country table. 3. Constraint method test insert into solider values ​​(4, 'Sicilian Archer', 3);
#Successfully inserted delete from country where id=3;
#This will cause the records with id 3 and 4 in the solider table to be set to NULL
update country set id=8 where id=1;
# Causes all records in the solider table where country_id is 1 to be set to NULL

With NO ACTION or RESTRICT mode (default)

1. Create a soldier table (sub-table) and establish a constraint relationship drop table if exists solider;
create table solider(
id int not null,
name varchar(30),
country_id int,
primary key(id),
foreign key(country_id) references country(id) on delete RESTRICT on update RESTRICT,
);

2. Reference integrity test insert into solider values(1,'Western European trainee infantry',1);
#insert successfully insert into solider values(2,'Maya short spearman',2);
#insert successfully insert into solider values(3,'Sicily Norman Knights',3)
#insert successfullyinsert into solider values(4,'French Swordsman',4);
#Insert failed because there is no faction with id 4 in the country table 3. Constraint method test insert into solider values(4, 'Western European Knights', 1);
#Successfully inserted delete from country where id=1;
#An error occurred. There are related records in the child table, so the corresponding records in the parent table cannot be deleted. That is, the arms table also has arms belonging to Western Europe, so the Western European forces in the parent table cannot be deleted alone. update country set id=8 where id=1;
#Error, there are related records in the child table, so the parent table cannot be modified

The above is the detailed explanation of MySQL foreign key constraints. For more information about MySQL foreign key constraints, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • Specific method to add foreign key constraints in mysql
  • MySQL foreign key constraint (FOREIGN KEY) case explanation
  • Summary of MySQL foreign key constraints and table relationships
  • Example explanation of MySQL foreign key constraints
  • Introduction to MySQL method of deleting table data with foreign key constraints
  • Simple implementation of ignoring foreign key constraints when deleting MySQL tables
  • How to disable foreign key constraint checking in MySQL child tables
  • How to create and delete foreign key constraints in MySQL

<<:  Detailed tutorial on installing CUDA9.0 on Ubuntu16.04

>>:  Detailed explanation of vue.js dynamic components

Recommend

Detailed tutorial on installing mysql on centos 6.9

1. Confirm whether MySQL has been installed. You ...

How to package the uniapp project as a desktop application

Installing Electron cnpm install electron -g Inst...

Use Javascript to develop sliding-nav navigation plug-in with sliding bar effect

Table of contents 1. Introduction 2. Usage 3. Dev...

React example showing file upload progress

Table of contents React upload file display progr...

Solution to the problem that Docker container cannot access Jupyter

In this project, the Docker container is used to ...

Web page layout should consider IE6 compatibility issues

The figure below shows the browser viewing rate i...

A brief discussion on the differences between FTP, FTPS and SFTP

Table of contents Introduction to FTP, FTPS and S...

Detailed tutorial on downloading mysql on Windows 10

MySQL versions are divided into Enterprise Editio...

Vue implements calling PC camera to take photos in real time

Vue calls the PC camera to take pictures in real ...

An article explains Tomcat's class loading mechanism

Table of contents - Preface - - JVM Class Loader ...

MySQL 5.7.18 winx64 installation and configuration method graphic tutorial

The installation of compressed packages has chang...

Detailed explanation of the execution order of JavaScript Alert function

Table of contents question analyze solve Replace ...

A brief discussion on DDL and DML in MySQL

Table of contents Preface 1. DDL 1.1 Database Ope...

Using Zabbix to monitor the operation process of Oracle table space

0. Overview Zabbix is ​​an extremely powerful ope...