The use of Mysql foreign keys

MySQL foreign keys (please make sure the database is of the innodb type) There are many articles on the Internet. Here I will reorganize them based on my own understanding. I won’t talk nonsense, and get to the point.
The role of foreign keys:

The main purpose of maintaining data consistency and integrity is to control the data stored in foreign key tables. To associate the two tables, the foreign key can only refer to the value of the column in the foreign table!

Let's create two tables

 1 CREATE TABLE `example1` (
 2   `stu_id` int(11) NOT NULL DEFAULT '0',
 3   `name` VARCHAR(11) NOT NULL DEFAULT '',
 4   `course_id` int(11) NOT NULL DEFAULT '0',
 5   `grade` float DEFAULT NULL,
 6   PRIMARY KEY (`stu_id`,`course_id`)
 7 ) engine=INNODB;
 8 CREATE TABLE `example2` (
 9   `id` int(11) NOT NULL,
10   `stu_id` int(11) DEFAULT NULL,
11   `course_id` int(11) DEFAULT NULL,
12   PRIMARY KEY (`id`),
13   KEY `f_ck` (`stu_id`,`course_id`),
14   CONSTRAINT `f_ck` FOREIGN KEY (`stu_id`, `course_id`) REFERENCES `example1` (`stu_id`, `course_id`)
15 ) engine=INNODB;
16 insert into example1 (stu_id,name,course_id,grade)values(1,'baidu',1,97.5),(2,'google',2,89);
17 insert into example2 (id,stu_id,course_id)values(1,1,1),(2,2,2); 

example1 table, which contains stu_id student number, name name, course_id course number, grade score

The example2 table contains id, stu_id student number, course_id course number, and then establishes a foreign key

Insert data into two tables separately.

We call the stu_id and course_id in example2 as foreign keys of the example2 table, example1 is the parent table, example2 is the child table, the two tables are associated, and the corresponding data in the parent table can only be deleted after the data in the child table is deleted.

Now let's delete a piece of data in example1

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325161538&siteId=291194637