当前位置:网站首页>Does MySQL support foreign keys
Does MySQL support foreign keys
2022-06-29 17:23:00 【Yisu cloud】
mysql Do you support foreign keys
This article mainly explains “mysql Do you support foreign keys ”, Interested friends might as well come and have a look . The method introduced in this paper is simple and fast , Practical . Now let Xiaobian take you to learn “mysql Do you support foreign keys ” Well !
mysql Support foreign keys . stay MySQL in , Foreign keys are mainly used to establish the relationship between master tables and slave tables , You can establish a connection for the data of two tables , Constrains the consistency and integrity of data in two tables ; When a record is deleted from the main table , The corresponding records from the table must be changed accordingly . A table can have one or more foreign keys , The foreign key can be null , If not null , Then the value of each foreign key must be equal to a value of the primary key in the primary table ; The number of columns and corresponding data types in the foreign key must be the same as those in the primary key of the primary table .
The operating environment of this tutorial :windows7 System 、mysql8 edition 、Dell G3 The computer .
mysql Support foreign keys .
MySQL Foreign keys (FOREIGN KEY)
A foreign key is a field in a specified table that matches another field in another table . Foreign keys set constraints on data in related tables , This makes MySQL Ability to maintain referential integrity .
Foreign keys are used to establish the relationship between the master table and the slave table , Establish a connection between the data of two tables , Constrains the consistency and integrity of data in two tables .
For two tables that have an association , The table where the primary key in the associated field is located is the primary table ( Parent table ), The table where the foreign key is located is the slave table ( Sub table ).
When a record is deleted from the main table , The corresponding records from the table must be changed accordingly . A table can have one or more foreign keys , The foreign key can be null , If not null , Then the value of each foreign key must be equal to a value of the primary key in the primary table .
Let's take a look at the following database diagram in the sample database .

We have two watches :customers and orders, Every customer has zero or more orders , Each order can only belong to one customer .customers Table and orders The relationship between tables is one to many , it orders from customerNumber Field to create a foreign key in the table specified by the .customers In the table customerNumber Fields and orders In the table customerNumber The primary key field is related .
customers Tables are called parent tables or reference tables ,orders Tables are called child tables or reference tables .
A foreign key can be a column or a group of columns . The columns in the child table usually refer to the primary key columns in the parent table .
A table can have multiple foreign keys , Each foreign key in a child table can reference a different parent table .
Rows in the child table must contain values that exist in the parent table , for example ,orders Each order record in the table must have customers surface customerNumber Exists in . therefore , Multiple orders can reference the same customer , This relationship is called a ( Customer ) To more than one ( Order ) Or one to many .
Sometimes , The child table and the parent table are the same . The foreign key refers to the primary key of the table , for example , Next employees surface :

reportTo Column is a foreign key , It refers to employeeNumber As employees The primary key column of the table , To reflect the reporting structure between employees , That is, each employee reports to another employee , Employees can have zero or more direct reports . We have a tutorial on self join to help you query data based on this table .
reportTo Foreign keys are also called recursive or self referencing foreign keys .
Foreign keys enforce referential integrity , Helps you automatically maintain data consistency and integrity . for example , You cannot create an order for a customer that does not exist .
Besides , You can customerNumber Set cascading on the deletion of foreign keys , In order to delete customers Customers in the table , All orders associated with the customer will also be deleted . This saves the use of multiple DELETE sentence or DELETE JOIN The time and energy of the statement .
Same as delete , You can also update for customerNumber Foreign key definitions cascade , So that multiple UPDATE Sentence or UPDATE JOIN Statement to execute cross table updates .
Be careful : stay MySQL in ,InnoDB The storage engine supports foreign keys , So you have to create InnoDB Tables can use foreign key constraints .
mysql When defining a foreign key , The following rules need to be followed :
The primary table must already exist in the database , Or the table that is currently being created . In the latter case , Then the master table and the slave table are the same table , Such a table is called a self reference table , This structure is called self referential integrity .
The primary key must be defined for the primary table .
Primary key cannot contain null value , But null values are allowed in foreign keys . in other words , As long as each non null value of the foreign key appears in the specified primary key , The content of this foreign key is correct .
Specify the column name or combination of column names after the table name of the main table . This column or combination of columns must be the primary key or candidate key of the main table .
The number of columns in the foreign key must be the same as the number of columns in the primary key of the primary table .
The data type of the column in the foreign key must be the same as that of the corresponding column in the primary key of the primary table .
Create foreign keys for tables
MySQL Create foreign key Syntax
The following syntax describes how to use the CREATE TABLE The foreign key is defined in the sub table of the statement .
CONSTRAINT constraint_nameFOREIGN KEY foreign_key_name (columns)REFERENCES parent_table(columns)ON DELETE actionON UPDATE action
Let's study grammar in more detail :
CONSTRAINT Clause allows you to define constraint names for foreign key constraints . If you omit it ,MySQL A name will be automatically generated .
FOREIGN KEY Clause specifies the column in the child table that references the primary key column in the parent table . You can put a foreign key name in FOREIGN KEY After Clause , Or let MySQL Create a name for you . Please note that ,MySQL Will be used automatically foreign_key_name Name create index .
REFERENCES Clause specifies the parent table and column referenced by the column in the child table . The number of columns in the specified child table and parent table FOREIGN KEY and REFERENCES It has to be the same .
ON DELETE Clause allows you to define the contents of records in the child table when deleting records in the parent table . If omitted ON DELETE Clause and delete records in the parent table that contain records in the child table ,MySQL Will refuse to delete . Besides ,MySQL It also provides you with operations , So that you can use other options , for example ON DELETE CASCADE , requirement MySQL Delete the records in the sub table , When the records in the parent table are deleted , Records will reference records in the parent table . If you do not want to delete the related records in the sub table , Please switch to ON DELETE SET NULL operation .MySQL The foreign key column value in the child table will be set to NULL When deleting records in the parent table , The condition is that the foreign key column in the child table must accept NULL value . Please note that , If you use ON DELETE NO ACTION or ON DELETE RESTRICT operation ,MySQL Will refuse to delete .
ON UPDATE Clause allows you to specify what happens to the rows in the child table when the rows in the parent table are updated . You can omit ON UPDATE Clause , So that when updating rows in the parent table MySQL Reject any updates to the rows in the child table .ON UPDATE CASCADE Operations allow you to perform cross table updates , And when the parent table is updated ON UPDATE SET NULL When the line in , The operation resets the values in the rows in the child table to the values NULL.ON UPDATE NO ACTION or UPDATE RESTRICT Action rejects any updates .
MySQL Create a table foreign key example
The following example creates a dbdemo Database and two tables :categories and products. Each category has one or more products and each product belongs to only one category .products In the table cat_id The field is defined with UPDATE ON CASCADE and DELETE ON RESTRICT Foreign keys for actions .
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;
Add foreign keys to the table
MySQL Add foreign key syntax
To add a foreign key to an existing table , Please use... With the above foreign key definition syntax ALTER TABLE sentence :
ALTER TABLE table_nameADD CONSTRAINT constraint_nameFOREIGN KEY foreign_key_name(columns)REFERENCES parent_table(columns)ON DELETE actionON UPDATE action;
MySQL Add a foreign key example
Now? , Let's add a new one called vendors New table of , And change products Table to include suppliers ID Field :
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 add a foreign key to a table products, Please use the following sentence :
ALTER TABLE productsADD FOREIGN KEY fk_vendor(vdr_id)REFERENCES vendors(vdr_id)ON DELETE NO ACTIONON UPDATE CASCADE;

Now? ,products The table has two foreign keys , A quote categories surface , Another reference vendors surface .
Here we are , I'm sure you're right “mysql Do you support foreign keys ” Have a deeper understanding of , You might as well put it into practice ! This is the Yisu cloud website , For more relevant contents, you can enter the relevant channels for inquiry , Pay attention to our , Continue to learn !
边栏推荐
- flink sql rownumber 报错。谁遇到过啊?怎么解决?
- Mysql高可用集群–MHA
- Simulink simulation mode
- R语言使用epiDisplay包的kap函数(kap.2.raters函数)计算Kappa统计量的值(总一致性、期望一致性)、对两个评分对象的结果进行一致性分析、评分的类别为多个类别
- 从居家办公中感悟适配器模式 | 社区征文
- sectigo ov泛域名证书一年一千五百九十元好用吗
- Help MySQL data analysis with databend
- Go语言多方式并发实现龟兔赛跑
- SLAM中的子图
- The fixed assets management system enables enterprises to dynamically master assets
猜你喜欢

LSB hidden items of stream carrier based on assembly implementation

Word2vec vector model of Wiki Chinese corpus based on deep learning

Subgraphs in slam

Viewing splitchunks code segmentation from MPX resource construction optimization

controller、service、dao之间的关系

手把手教你在windows上安装mysql8.0最新版本数据库,保姆级教学

windows平台下的mysql启动等基本操作

Redis 原理 - Sorted Set (ZSet)

mysql查询视图命令是哪个

基于深度学习的Wiki中文语料词word2vec向量模型
随机推荐
浏览器大尺寸截屏
R语言使用glm函数构建泊松对数线性回归模型处理三维列联表数据构建饱和模型、使用exp函数和coef函数获取模型所有变量的事件密度比(Incidence Density Ratio,IDR)并解读
Mysql中锁的使用场景是什么
SpingMVC请求和响应
PCB板框的绘制——AD19
How to establish and use KUKA subroutines / functions
L'intercepteur handlerinterceptor personnalisé permet l'authentification de l'utilisateur
Word2vec vector model of Wiki Chinese corpus based on deep learning
线段树、树状数组模板(复制粘贴确实好用)
卷妹带你学数据库---5天冲刺Day4
ICML 2022 | transferable imitation learning method based on decoupling gradient optimization
反射
[R language data science]: Text Mining (taking Trump's tweet data as an example)
0基础自学STM32(野火)——寄存器点亮LED
微博评论高性能高可用架构设计(架构实战营 模块五作业)
Kubernetes deployment dashboard (Web UI management interface)
卷妹带你学数据库---5天冲刺Day1
What are the project management systems suitable for small and medium-sized enterprises?
Inheritablethreadlocal resolves message loss during message transmission between parent and child threads in the thread pool
PCB frame drawing - ad19