1.数据表外键的概念及作用
如果有两张数据表,则在建立数据表时设置外键,有利于保持这两张数据表数据的一致性及完整性。
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 |
向test_foreign表中添加数据时,test_id字段的值必须存在于test数据表中,否则会报错。
比如,插入值为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 |
4.删除外键关联表中的数据
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。