mysql中MyISAM和InnoDB存储引擎都支持外键(foreign key),但是MyISAM只能支持语法,却不能实际使用。下面通过例子记录下InnoDB中外键的使用方法:
创建主表:
mysql> create table parent(id int not null,primary key(id)) engine=innodb;
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 cascade) engine=innodb;
Query OK, 0 rows affected (0.04 sec)
插入主表测试数据:
mysql> insert into parent values(1),(2),(3);
Query OK, 3 rows affected (0.03 sec)
Records: 3 Duplicates: 0 Warnings: 0
插入从表测试数据:
mysql> insert into child values(1,1),(1,2),(1,3),(1,4);
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`test/child`, CONSTRAINT `child_ibfk_1` FOREIGN KEY (`parent_id`) REFERENCES `parent` (`id`) ON DELETE CASCADE)
因为4不在主表中,插入时发生了外键约束错误。
只插入前三条:
mysql> insert into child values(1,1),(1,2),(1,3);
Query OK, 3 rows affected (0.03 sec)
Records: 3 Duplicates: 0 Warnings: 0
成功!
删除主表记录,从表也将同时删除相应记录:
mysql> delete from parent where id=1;
Query OK, 1 row affected (0.03 sec)
mysql> select * from child;
+——+———–+
| id | parent_id |
+——+———–+
| 1 | 2 |
| 1 | 3 |
+——+———–+
2 rows in set (0.00 sec)
更新child中的外键,如果对应的主键不存在,则报错:
mysql> update child set parent_id=4 where parent_id=2;
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`test/child`, CONSTRAINT `child_ibfk_1` FOREIGN KEY (`parent_id`) REFERENCES `parent` (`id`) ON DELETE CASCADE)
如果改