[MySQL] Foreign key constraints and foreign key strategies

1. What is a foreign key constraint?

        Foreign key constraints ( FOREIGN KEY , abbreviated as FK ) are used to implement the referential integrity of database tables. Foreign key constraints can make two tables closely combined, especially for cascading operations of modification or deletion, which will ensure data integrity.
        A foreign key means that the value of a field in a table depends on the value of a field in another table, and the dependent field must have a primary key constraint or a unique constraint . The dependent table is usually called the parent table or the main table, and the table with foreign key constraints is called the child table or the slave table.

2. Examples of foreign key constraints

        If you want to express the relationship between students and classes, you must first have two tables, the student table and the class table, and then there is a field in the student table called stu_class (this field indicates the class the student is in), and the value range of this field is determined by the class The value of the primary key cla_no field in the table (this field represents the class number) is determined. Then the class table is the main table, the student table is the slave table, and the stu_class field is the foreign key of the student table. The relationship between the student table and the class table is established through the stu_class field.

If the student table is designed in this way, there are two disadvantages:

  • Disadvantage 1: data duplication
  • Disadvantage 2: When modifying class data, multiple records need to be changed

The student table can be designed like this:

that's all,

The class table is known as the parent table and the class number is its primary key

The student table is called a child table and the class name is its foreign key .

3. SQL display of foreign key constraints

1. The child table depends on the parent table, so create the parent table first:

create table t_class(
	cno int(4) primary key auto_increment,
	cname varchar(10) not null,
	room char(4)
);

2. Add data to the table class:

insert into t_class values (null,'Python一班','r803');
insert into t_class values (null,'Python二班','r416');
insert into t_class values (null,'Java一班','r103');

3. Create a subtable: student table t_student

When creating a foreign key, the column names can be different, but the column type and its length should be consistent with the primary key.

create table t_student(
	sno int(6) primary key auto_increment,
	sname varchar(5) not null,
	classno int(4)
);

4. Add student information

insert into t_student values (null,'张三',1);
insert into t_student values (null,'李四',1);
insert into t_student values (null,'王五',1);

5. Associate the master table with the slave table

Need to add foreign key constraints, foreign key constraints only table-level constraints, no column-level constraints.

Add a foreign key constraint to the subtable t_student, specify the constraint name as fk_stu_classno, and associate the foreign key classno of t_student with the primary key cno of t_class:

alter table t_student add constraint fk_stu_classno foreign key (classno) references t_class (cno);

6. Test whether the association is successful

Currently, the student table looks like this:

The class table is as follows:

Test 1: Delete class 1 in the t_class table

Expected result: It should be impossible to delete, because in the student table associated with the class table, there are students in class 1, it should be possible to delete classes 2 and 3, because students do not have classes 2 and 3;

delete from t_class cno=1;

Execution returns 1451 error:

> 1451 - Cannot delete or update a parent row: a foreign key constraint fails (`database_me`.`t_student`, CONSTRAINT `fk_stu_classno` FOREIGN KEY (`classno`) REFERENCES `t_class` (`cno`))

Because it is affected by foreign key constraints.

Test Two: Delete Class 2

Deleted successfully.

Test 3: Add a piece of data in the student table, this student is in class 3, and then try to delete class 3

insert into t_student values (null,"老六",3);

Delete class 3:

delete from t_class where cno=3;

At this point, a 1451 error will be returned, indicating that the primary key is already constrained by a foreign key.

Test 4: Add a classmate with class 4 to the child table with foreign key

insert into t_student values (null,"小七",4);

Returns 1452 error:

> 1452 - Cannot add or update a child row: a foreign key constraint fails (`database_me`.`t_student`, CONSTRAINT `fk_stu_classno` FOREIGN KEY (`classno`) REFERENCES `t_class` (`cno`))

Because there is no class 4 in the main table.

Fourth, delete the master/slave table

You need to delete the slave table first, and then delete the master table, otherwise it cannot be deleted.

Deleting the main table first will return the following error:

> 3730 - Cannot drop table 't_class' referenced by a foreign key constraint 'fk_stu_classno' on table 't_student'.

Five, foreign key strategy

Because some operations have caused confusion in the class table and student table data, now re-create these two tables for the following demonstration.

Requirement: Want to delete class 2

But it cannot be deleted directly, because there are foreign key constraints, we can consider adding a foreign key strategy .

1. Strategy 1: no action No operation is allowed

You can first change the class number of the class 2 students to null

update t_student set classno=null where classno=2;

delete again 

delete from t_class where cno=2;

2. Strategy 2: cascade cascade operation: when operating the master table, it affects the foreign key information of the slave table.

Before adding the cascading operation, try to update the class number:

update t_class set cno=5 where cno=3;

Returns 1451 error:

> 1451 - Cannot delete or update a parent row: a foreign key constraint fails (`database_me`.`t_student`, CONSTRAINT `fk_stu_classno` FOREIGN KEY (`classno`) REFERENCES `t_class` (`cno`))

To use the cascade cascade operation, you need to delete the previous foreign key constraints:

alter table t_student drop foreign key fk_stu_classno;

Then re-add the foreign key constraint:

alter table t_student
    add constraint fk_stu_classno
        foreign key (classno) references t_class (cno)
            on update cascade on delete cascade
;

on update cascade on delete cascade means that there will be cascading operations when updating and deleting.

Try to update the class number again:

update t_class set cno=5 where cno=3;

Try the delete operation, delete the class whose class number is 5, before deleting, you can see that there are 5 students in the student table:

Delete 5 classes from the class table:

delete from t_class where cno=5;

View the class table:

Look at the student table again:

It can be seen that when the master table of the cascade operation changes, the data of the slave table will also change accordingly. Cascading operations should be used with caution, as it has a greater impact on the production library.

3. Strategy 3: set null operation

Remove previous foreign key constraints:

alter table t_student drop foreign key fk_stu_classno;

Add a new foreign key constraint, using the null operation of the foreign key strategy:


alter table t_student add constraint 
	fk_stu_classno foreign key (classno) references t_class (cno) 
		on update set null on delete set null
		;	

Try to update the class table class number:

update t_class set cno=8 where cno=1;

View the class table:

To view the student table:

The cascading operation of strategy 2 and the blanking operation of strategy 3 can be used in combination . For example, the cascading operation is added for the update operation, and the blanking operation is added for the delete operation:

alter table t_student add constraint
	fk_stu_classno foreign key (classno) references t_class (cno)
		update cascade on delete set null
		;

The application scenarios of the two are different, for example:

When deleting the circle of friends, the comments below will also be deleted together, so the deletion operation of the circle of friends can use the cascade operation;

When disbanding a class, the students in the class still exist, and the class information of the students can be set to empty, because a new class will be assigned to the students later, so the operation of disbanding the class can add a blank operation.

Guess you like

Origin blog.csdn.net/hold_on_qlc/article/details/130127739