创建外键

方法一

drop table if exists base_info;

create table base_info(

id varchar(64) not null comment '主键',

-- 其他字段省略

primary key(id)

)engine=innodb default charset=utf8 comment '基本信息表';

子表

drop table if exists sub_info;

create table sub_info(

id varchar(64) not null comment '主键',

base_info_id varchar(64) not null comment 'base_info表主键' references base_info(id),

-- 其他字段省略

primary key(id)

)engine=innodb default charset=utf8 comment '子信息表';

有两个注意点

references关键字放在后面,不能放在not null后comment前;该种方式用Navicat设计表查看时在外键中看不到信息

方法二

主表不变,子表如下

drop table if exists sub_info;

create table sub_info(

id varchar(64) not null comment '主键',

base_info_id varchar(64) not null comment 'base_info表主键',

-- 其他字段省略

primary key(id)

)engine=innodb default charset=utf8 comment '子信息表';

-- 添加外键

alter table sub_info add constraint fk_base_info_id foreign key(base_info_id) references base_info(id);

这种方式再用Navicat设计表去查看,可以看到外键信息。

参考文章

文章来源

评论可见,请评论后查看内容,谢谢!!!
 您阅读本篇文章共花了: