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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值