您的位置:首页 > 数据库 > MySQL

mysql中的外键使用

2008-06-04 15:29 363 查看
这两天有人问mysql中如何加外键,今天抽时间总结一下。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)

如果改为主表中存在的值,则可以正常更新:mysql> update child set parent_id=2 where parent_id=2;
Query OK, 0 rows affected (0.01 sec)
Rows matched: 1 Changed: 0 Warnings: 0
如果要在父表中更新或者删除一行,并且在子表中也有一行或者多行匹配,此时子表的操作有5个选择:· CASCADE: 从父表删除或更新且自动删除或更新子表中匹配的行。ON
DELETE CASCADE和ON UPDATE CASCADE都可用。在两个表之间,你不应定义若干在父表或子表中的同一列采取动作的ON UPDATE
CASCADE子句。
· SET NULL:
从父表删除或更新行,并设置子表中的外键列为NULL。如果外键列没有指定NOT NULL限定词,这就是唯一合法的。ON DELETE SET NULL和ON
UPDATE SET NULL子句被支持。
· NO ACTION: 在ANSI SQL-92标准中,NO
ACTION意味这不采取动作,就是如果有一个相关的外键值在被参考的表里,删除或更新主要键值的企图不被允许进行(Gruber,
掌握SQL, 2000:181)。 InnoDB拒绝对父表的删除或更新操作。

· RESTRICT: 拒绝对父表的删除或更新操作。NO
ACTION和RESTRICT都一样,删除ON DELETE或ON UPDATE子句。(一些数据库系统有延期检查,并且NO
ACTION是一个延期检查。在MySQL中,外键约束是被立即检查的,所以NO ACTION和RESTRICT是同样的)。

· SET DEFAULT:
这个动作被解析程序识别,但InnoDB拒绝包含ON DELETE SET DEFAULT或ON UPDATE SET DEFAULT子句的表定义。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息