sql语句格式:
· 添加外键约束:alter table 从表 add constraint 外键(形如:FK_从表_主表) foreign key (从表外键字段) references 主表(主键字段);
如果mysql报错:Error Code: 1215. Cannot add foreign key constraint (foreign keys)
检查 主从表两个字段的属性是否一致
将member表id键改为bigint:alter table member modify column id BIGINT;
执行时发现如下错误:
ERROR 1025 (HY000): Error on rename of ‘.\test\#sql-c68_10’ to ‘.\test\member’ (errno: 150)
原因:
member表的id主键字段是另外一张address的外键,修改主表id字段类型会导致主表与外键关联表字段不一致。
解决方法:
- 找到外键关联表,找到外键名字。
- 删除外键约束
- 修改主表(member)id字段类型:alter table member modify column id bigint;
- 修改辅表(address)member_id字段类型:alter table address modify column member_id bigint;
- 将删除的外键补上:alter table address add constraint fk_member_address foreign key (member_id) references member(id);