创建完表后添加
语法:
alter table `表名` add constraint 自定义外键名
foreign key (外键字段)
references `关联表名`(`关联字段`);
示例:
alter table `Score` add constraint score_subject
foreign key(`SubjectId`)
references `Subject`(`SubjectId`);
- 外键值可以为
null
- 外键字段与引用一张表的某个字段的时候,被引用的字段必须具有
unique
(唯一)约束 - 有了外键引用以后,表分为父表和子表,引用的表为父表,被引用的表为子表
- 创建时先创建父表
- 删除时先创建子表
- 插入时先插入父表数据
创建表的时候添加
create table if not exists `father_table`(
`test_field1` int(4) primary key
)charset='utf8mb4';
create table if not exists `child_table`(
`test_field1` int(4),
foreign key(`test_field1`) references `father_table`(`test_field1`)
)charset='utf8mb4';