Mysql外键关联表的相关总结
2014-04-02 16:19
309 查看
1.数据表外键的概念及作用
如果有两张数据表,则在建立数据表时设置外键,有利于保持这两张数据表数据的一致性及完整性。
2.创建数据表外键的方法
比如,有两张数据表test和test_foreign。
其中,创建test数据表的sql语句为
创建test_foreign数据表的sql语句为
其中,test_id是与test表中的主键id相关联的外键,并且当test中的值删除,本表中对应的列也会删除;当外键的值改变,本表中对应的列值改变。
3.向含有外键的表中添加数据
假设test中已存在若干数据
向test_foreign表中添加数据时,test_id字段的值必须存在于test数据表中,否则会报错。
比如,插入值为4的数据,会出现以下错误:
因此只能添加test中id已存在的值。
假设,test_foreign有下列数据
4.删除外键关联表中的数据
查看test_foreign表中的数据则会发现,表中test_id=1的数据也同时被删除了。
5.修改外键关联表的数据
修改外键关联表中字段值,含有外键的数据表相应字段值也会改变。
(由于这个例子中test_id是test表的主键,所以无法改变主键id的值)
6.删除数据表
删除数据表,应先删除含有外键的数据表,再删外键关联的数据表。否则,会报错。
例如,
应先删除test_foreign,再删除test。
如果有两张数据表,则在建立数据表时设置外键,有利于保持这两张数据表数据的一致性及完整性。
2.创建数据表外键的方法
比如,有两张数据表test和test_foreign。
其中,创建test数据表的sql语句为
create table test( id int not null primary key auto_increment, info varchar(1000) not null)
创建test_foreign数据表的sql语句为
create table test_foreign( id int not null primary key auto_increment, test_id int, foreign key(test_id) references test(id) on delete cascade on update cascade)
其中,test_id是与test表中的主键id相关联的外键,并且当test中的值删除,本表中对应的列也会删除;当外键的值改变,本表中对应的列值改变。
3.向含有外键的表中添加数据
假设test中已存在若干数据
id | info |
1 | adsfasdf |
2 | qwerasdf |
3 | fgjhasdwe |
比如,插入值为4的数据,会出现以下错误:
mysql> insert into test_foreign values(null,4); ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`test/test_foreign`, CONSTRAINT `test_foreign_ibfk_1` FOREIGN KEY (`test_id`) REFERENCES `test` (`id`) ON DELETE CASCADE ON UPDATE CASCADE) mysql>
因此只能添加test中id已存在的值。
假设,test_foreign有下列数据
id | test_id |
1 | 1 |
2 | 2 |
3 | 3 |
4 | 3 |
5 | 1 |
6 | 2 |
delete from test where id=1
查看test_foreign表中的数据则会发现,表中test_id=1的数据也同时被删除了。
5.修改外键关联表的数据
修改外键关联表中字段值,含有外键的数据表相应字段值也会改变。
(由于这个例子中test_id是test表的主键,所以无法改变主键id的值)
6.删除数据表
删除数据表,应先删除含有外键的数据表,再删外键关联的数据表。否则,会报错。
例如,
mysql> drop table test -> ; ERROR 1217 (23000): Cannot delete or update a parent row: a foreign key constraint fails mysql>
应先删除test_foreign,再删除test。
相关文章推荐
- MySQL外键相关知识
- MySQL相关问题总结
- MySQL复制相关技术的简单总结
- mysql添加外键失败原因总结
- mysql相关命令的作用总结
- 项目总结1—Mysql创建表外键约束报错总结
- mysql由于外键关联无法删除数据
- MySQL忽略外键关联
- mysql 外键 相关
- 总结三种MySQL外键约束方式
- Oracle技术之和外键相关的阻塞和死锁问题总结(四)
- MySQL学习总结----数据库相关操作
- [引]MySQL INNODB类型表的外键关联设置
- MySQL笔记-外键创建失败总结
- 深入mysql外键关联问题的详解
- 解析MySQL创建外键关联错误 - errno:150
- MySQL中NULL值相关技巧总结
- 关于linux下使用phpmyadmin给mysql表关联外键的问题和解决办法
- [引]MySQL INNODB类型表的外键关联设置
- 总结mysql的三种外键约束方式