MYSQL-Foreign key constraints (graphic)

Introduction

Conditions for using foreign keys:

  1. The two tables must be InnoDB tables, MyISAM tables do not support foreign keys temporarily
  2. The foreign key column must be indexed, MySQL 4.1.2 and later versions will automatically create the index when the foreign key is created
  3. The columns of the two tables of the foreign key relationship must be of similar data types, that is, columns that can be converted to each other, such as int and tinyint, but not int and char, and the associated fields must be unique

Four types of foreign key constraints

RESTRICT (constraint): If it appears when deleting, it means that the foreign key primary key did record (record in the primary table) cannot be deleted directly. You must delete all the foreign key primary keys in the dept_id field of the constrained table (from the table). The record corresponding to the value can delete the foreign key constraint (record in the main table). The test found that the default setting is not selected in Navicat.

NO ACTION: It is equivalent to RESTRICT in MySQL. The reason is as follows: restrict is to check whether there is corresponding data in the table before modifying or deleting. If there is, reject the operation, and no action is the source standard sql, in some databases , Will delay the check, that is, check whether there is corresponding data in the slave table after modification or deletion, if there is, reject the operation, but in MySQL, foreign key constraints will be checked immediately, so the two are equivalent

CASCADE: Delete When this option is selected, when deleting a record in the primary table, the record with the id value of the secondary table associated with the primary key id in the primary table will also be deleted. It is recommended not to choose.

SET NULL: When deleting this option, if the value of the constrained field from the table (in the table where the constrained field is located) is set to be nullable, then when the record of the main table is deleted, the one in the main table is deleted The primary key value corresponding to the record (the value of the constrained slave table field) appears in the corresponding field in the slave table, and the value of the constrained field of the record will become NULL.

The most commonly used is to select the constraint that RESTRICT does not allow deletion, or to select SET NULL to delete the value table to be empty.

Example

Step 1: Create two tables: department table dept and employee table emp, and associate the foreign key of emp.dno to dept.did

CREATE TABLE `dept` (
  `did` int(10) NOT NULL AUTO_INCREMENT,
  `dname` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`did`),
  UNIQUE KEY `dname` (`dname`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci

CREATE TABLE `emp` (
  `eid` int(10) NOT NULL AUTO_INCREMENT,
  `ename` varchar(30) COLLATE utf8_unicode_ci DEFAULT NULL,
  `dno` int(10) DEFAULT NULL,
  `sal` double(7,2) DEFAULT NULL,
  PRIMARY KEY (`eid`),
  KEY `fk_dno_did` (`dno`),
  CONSTRAINT `fk_dno_did` FOREIGN KEY (`dno`) REFERENCES `dept` (`did`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci

mysql> desc dept;
+-------+--------------+------+-----+---------+----------------+
| Field | Type         | Null | Key | Default | Extra          |
+-------+--------------+------+-----+---------+----------------+
| did   | int(10)      | NO   | PRI | NULL    | auto_increment |
| dname | varchar(255) | NO   | UNI | NULL    |                |
+-------+--------------+------+-----+---------+----------------+
mysql> desc emp;
+-------+-------------+------+-----+---------+----------------+
| Field | Type        | Null | Key | Default | Extra          |
+-------+-------------+------+-----+---------+----------------+
| eid   | int(10)     | NO   | PRI | NULL    | auto_increment |
| ename | varchar(30) | YES  |     | NULL    |                |
| dno   | int(10)     | YES  | MUL | NULL    |                |
| sal   | double(7,2) | YES  |     | NULL    |                |
+-------+-------------+------+-----+---------+----------------+

Step 2: Initialize table data

insert into dept values (1,'技术部'),(2,'人事部');
insert into emp values (1,'张三',1,10000),(2,'李四',2,20000);

mysql> select * from dept order by did;
+-----+--------+
| did | dname  |
+-----+--------+
|   1 | 技术部 |
|   2 | 人事部 |
+-----+--------+
mysql> select * from emp order by eid;
+-----+-------+-----+----------+
| eid | ename | dno | sal      |
+-----+-------+-----+----------+
|   1 | 张三  |   1 | 10000.00 |
|   2 | 李四  |   2 | 20000.00 |
+-----+-------+-----+----------+

Step 3: When there is associated data, delete or update the dept data table, or report an error when inserting or updating emp (four cases)

delete from dept where did=1;
1451 - Cannot delete or update a parent row: a foreign key constraint fails (`test`.`emp`, CONSTRAINT `fk_dno_did` FOREIGN KEY (`dno`) REFERENCES `dept` (`did`))

update dept set did=3 where did=1;
1451 - Cannot delete or update a parent row: a foreign key constraint fails (`test`.`emp`, CONSTRAINT `fk_dno_did` FOREIGN KEY (`dno`) REFERENCES `dept` (`did`))

insert into emp values (null,'张三',4,10000);
1452 - Cannot add or update a child row: a foreign key constraint fails (`test`.`emp`, CONSTRAINT `fk_dno_did` FOREIGN KEY (`dno`) REFERENCES `dept` (`did`))

update emp set dno=3 where eid=1;
1452 - Cannot add or update a child row: a foreign key constraint fails (`test`.`emp`, CONSTRAINT `fk_dno_did` FOREIGN KEY (`dno`) REFERENCES `dept` (`did`))

Extension: other constraint types

  1. Primary key constraint PRIMARY KEY
  2. UNIQUE
  3. Not NULL constraint
  4. Default value constraint DEFAULT

Guess you like

Origin blog.csdn.net/magentodaddy/article/details/108288452