百分百源码网-让建站变得如此简单! 登录 注册 签到领金币!

主页 | 如何升级VIP | TAG标签

当前位置: 主页>网站教程>数据库> mysql中的外键使用详解
分享文章到:

mysql中的外键使用详解

发布时间:01/15 来源: 浏览: 关键词:
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)

打赏

打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

百分百源码网 建议打赏1~10元,土豪随意,感谢您的阅读!

共有4人阅读,期待你的评论!发表评论
昵称: 网址: 验证码: 点击我更换图片
最新评论

本文标签

广告赞助

能出一分力是一分吧!

订阅获得更多模板

本文标签

广告赞助

订阅获得更多模板