教程集 www.jiaochengji.com
教程集 >  数据库  >  mysql  >  正文 mysql中的外键使用详解

mysql中的外键使用详解

发布时间:2017-02-23   编辑:jiaochengji.com
教程集为您提供mysql中的外键使用详解等资源,欢迎您收藏本站,我们将为您提供最新的mysql中的外键使用详解资源
mysql中的外键小编很少用到可能说几乎没有用到过了,今天我们来看一篇关于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中的外键使用详解
学习MySQL数据分页查询(limit用法)
解析mysql数据仓库infobright的使用方法
MySQL常见错误代码解析
mysql中explain语法的用法
linux下mysql添加用户、删除用户、授权、修改密码
详解:修改mysql默认字符集的两种方法
MySQL命令行修改密码(示例)
mysql explain用法学习
mysql中explain用法详解

[关闭]
~ ~