不设置引用选项时 默认为restrict效果同no action

1,先删除父表的话 会报错 2,只能先删除子表中的记录

  1. mysql> create table parent(id int not null primary key);
  2. Query OK, 0 rows affected (0.04 sec)
  3. mysql> create table child(id int,parent_id int,foreign key(parent_id) references parent(id));
  4. Query OK, 0 rows affected (0.04 sec)
  5. mysql> insert into parent select 1;
  6. Query OK, 1 row affected (0.01 sec)
  7. Records: 1 Duplicates: 0 Warnings: 0
  8. mysql> insert into parent select 2;
  9. Query OK, 1 row affected (0.01 sec)
  10. Records: 1 Duplicates: 0 Warnings: 0
  11. mysql> select * from parent;
  12. +----+
  13. | id |
  14. +----+
  15. | 1 |
  16. | 2 |
  17. +----+
  18. 2 rows in set (0.00 sec)
  19. mysql> insert into child select 1,1;
  20. Query OK, 1 row affected (0.01 sec)
  21. Records: 1 Duplicates: 0 Warnings: 0
  22. mysql> insert into child select 2,2;
  23. Query OK, 1 row affected (0.01 sec)
  24. Records: 1 Duplicates: 0 Warnings: 0
  25. mysql> select * from child;
  26. +------+-----------+
  27. | id | parent_id |
  28. +------+-----------+
  29. | 1 | 1 |
  30. | 2 | 2 |
  31. +------+-----------+
  32. 2 rows in set (0.00 sec)
  33. mysql> delete from parent where id = 1;
  34. 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`))
  35. mysql>
  36. mysql>
  37. mysql> delete from child where id = 1;
  38. Query OK, 1 row affected (0.01 sec)
  39. mysql> delete from parent where id = 1;
  40. Query OK, 1 row affected (0.01 sec)
  41. mysql> drop table parent;
  42. ERROR 1217 (23000): Cannot delete or update a parent row: a foreign key constraint fails
  43. mysql> drop table child;
  44. Query OK, 0 rows affected (0.02 sec)
  45. mysql> drop table parent;
  46. 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)