mysql foreign key

Introduction

MySQL's foreign key constraints are used to establish a link between two table data, where a field in one table is constrained by the corresponding field in the other table . In other words, to set foreign key constraints, there must be at least two tables. The constrained table is called the slave table (child table), and the other is called the master table (parent table), which belongs to the master-slave relationship.

Table description

There are now two tables my_class (master table) and my_stu (slave table). The master table and the slave table are connected through id.
SQL statement to create table:

#主表
CREATE table my_class(
	id int PRIMARY KEY,
	`name` VARCHAR(32) not null
)
#从表
CREATE table my_stu(
	id int PRIMARY KEY,
	`name` VARCHAR(32),
	class_id int ,
	foreign key(class_id) REFERENCES my_class(id)
)

How do foreign keys reflect constraints?

1. When inserting data from a table, there must be a corresponding foreign key in the main table.
my_class table (main table):

id (primary key) name
1 small class
2 middle class
3 Big class
insert into my_stu(id,name,class_id) values(1,"小花",4); #错误,class_id=4在主表中找不到对应的id=4
insert into my_stu(id,name,class_id) values(1,"小花",3); #正确,符合外键约束规范,主表中存在id=3

2. When deleting data from the main table, be sure to ensure that there is no data associated with the deleted data in the slave table.
For example, the my_stu table currently exists:

id (primary key) name class_id (foreign key)
1 floret 1
2 Xiaohong 2
3 Xiao Zhang 3

Because (1, floret, 1) exists in the table, the following deletion will report an error.

delete from my_class where id=1; #错误

The associated data from the slave table should be deleted first, and then the data from the master table should be deleted.

delete from my_stu where class_id=1;#删除从表关联数据
delete from my_class where id=1; 

Precautions

  1. The main table field pointed to by the foreign key must be primary key or unique
  2. The table must be innodb to support foreign keys
  3. The foreign key and primary key types must be consistent
  4. The foreign key can be null, and when it is null, there does not need to be a corresponding null in the main table.

Guess you like

Origin blog.csdn.net/weixin_44866921/article/details/132882882
Recommended