不设置引用选项时 默认为restrict效果同no action
1,先删除父表的话 会报错 2,只能先删除子表中的记录
mysql> create table parent(id int not null primary key);
Query OK, 0 rows affected (0.04 sec)
mysql> create table child(id int,parent_id int,foreign key(parent_id) references parent(id));
Query OK, 0 rows affected (0.04 sec)
mysql> insert into parent select 1;
Query OK, 1 row affected (0.01 sec)
Records: 1 Duplicates: 0 Warnings: 0
mysql> insert into parent select 2;
Query OK, 1 row affected (0.01 sec)
Records: 1 Duplicates: 0 Warnings: 0
mysql> select * from parent;
+----+
| id |
+----+
| 1 |
| 2 |
+----+
2 rows in set (0.00 sec)
mysql> insert into child select 1,1;
Query OK, 1 row affected (0.01 sec)
Records: 1 Duplicates: 0 Warnings: 0
mysql> insert into child select 2,2;
Query OK, 1 row affected (0.01 sec)
Records: 1 Duplicates: 0 Warnings: 0
mysql> select * from child;
+------+-----------+
| id | parent_id |
+------+-----------+
| 1 | 1 |
| 2 | 2 |
+------+-----------+
2 rows in set (0.00 sec)
mysql> delete from parent where id = 1;
ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constraint fails (`blog`.`child`, CONSTRAINT `child_ibfk_1` FOREIGN KEY (`parent_id`) REFERENCES `parent` (`id`))
mysql>
mysql>
mysql> delete from child where id = 1;
Query OK, 1 row affected (0.01 sec)
mysql> delete from parent where id = 1;
Query OK, 1 row affected (0.01 sec)
mysql> drop table parent;
ERROR 1217 (23000): Cannot delete or update a parent row: a foreign key constraint fails
mysql> drop table child;
Query OK, 0 rows affected (0.02 sec)
mysql> drop table parent;
Query OK, 0 rows affected (0.02 sec)
级联操作 设置引用选项为set null
mysql> create table parent(id int primary key);
Query OK, 0 rows affected (0.04 sec)
mysql> create table child(id int,parent_id int,foreign key(parent_id) references parent(id) on delete set null);
Query OK, 0 rows affected (0.05 sec)
mysql> insert into parent select 1;
Query OK, 1 row affected (0.01 sec)
Records: 1 Duplicates: 0 Warnings: 0
mysql> insert into parent select 2;
Query OK, 1 row affected (0.01 sec)
Records: 1 Duplicates: 0 Warnings: 0
mysql> insert into child select 1,1;
Query OK, 1 row affected (0.01 sec)
Records: 1 Duplicates: 0 Warnings: 0
mysql> insert into child select 2,2;
Query OK, 1 row affected (0.01 sec)
Records: 1 Duplicates: 0 Warnings: 0
mysql> delete from parent where id = 1;
Query OK, 1 row affected (0.01 sec)
mysql> select * from child;
+------+-----------+
| id | parent_id |
+------+-----------+
| 1 | NULL |
| 2 | 2 |
+------+-----------+
2 rows in set (0.00 sec)