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)