外键具有保持数据完整性和一致性的机制,对业务处理有着很好的校验作用。
白话简介
user 表:id 为主键
profile 表: uid 为主键
简单来说,若表 profile 的 uid 列 作为表外键(外建名称:user_profile),以表 user 做为主表,以其 id列 做为参照(references),且联动删除/更新操作(on delete/update cascade)。则 user 表 中删除 id 为 1 的记录,会联动删除 profile 中 uid 为 1 的记录。user 表中更新 id 为 1 的记录至 id 为 2,则profile 表中 uid 为 1 的记录也会被联动更新至 uid 为 2,这样即保持了数据的完整性和一致性。
B 存在外键 b_f_k,以 A 表的 a_k 作为参照列,则 A 为主表,B 为从表,A 中某记录更新或删除时将会联动 B 中外键与其关联对应的记录做更新或删除操作。
alter table `profile`
add constraint `user_profile` foreign key (`uid`)
references `user`(`id`) on delete cascade on update cascade;
在profile中为uid列添加名为user_profile的外键,且此外键的参照为user表的id列,关联的操作为删除和更新
正文讲解
1、表引擎必须为InnoDB,MyISAM不支持
2、外键必须建立索引(可以为普通、主键、唯一,事先不建立的话会自动创建一个