mysql中怎么给一张表中添加两个外键我添加时候一直报错。
答案:2 悬赏:0
解决时间 2021-02-21 08:37
- 提问者网友:巴黎塔下许过得承诺
- 2021-02-20 17:14
mysql中怎么给一张表中添加两个外键我添加时候一直报错。
最佳答案
- 二级知识专家网友:滚刀废物浮浪人
- 2021-02-20 17:39
当发生此类的错误的时候,从三个角度入手:
1、确保主表有主键。
2、确保主从表数据引擎为InnoDB类型。
3、确定从表外键字段类型与主表一致。
1、确保主表有主键。
2、确保主从表数据引擎为InnoDB类型。
3、确定从表外键字段类型与主表一致。
全部回答
- 1楼网友:无字情书
- 2021-02-20 18:52
我观察到你的 emp 表的 username 列, 已经是 有 uni 的 key 了
也就是那个 emp 表的 username 是唯一的了。
因此, 理论上
foreign key(username) references emp(username),
这个应该没有问题。
但是那个
foreign key (name) references emp (name)
由于 emp 表的 name 列, 是允许有重复行的。
因此你无法创建外键。
下面就是一个 失败的例子代码, 你可以参考一下
-- 创建测试主表. 无主键.
create table test_main2 (
id int not null,
value varchar(10)
);
-- 创建测试子表.
create table test_sub2 (
id int not null,
main_id int,
value varchar(10),
primary key(id)
);
-- 插入测试主表数据.
insert into test_main2(id, value) values (1, 'one');
insert into test_main2(id, value) values (2, 'two');
-- 插入测试子表数据.
insert into test_sub2(id, main_id, value) values (1, 1, 'oneone');
insert into test_sub2(id, main_id, value) values (2, 2, 'twotwo');
mysql> alter table test_sub2
-> add constraint main_id_cons2
-> foreign key (main_id)
-> references test_main2(id);
error 1005 (hy000): can't create table 'test.#sql-608_1' (errno: 150)
默认情况下,无法创建外键
需要创建 unique 约束
mysql> alter table test_main2
-> change column id id int unique;
query ok, 2 rows affected (0.17 sec)
records: 2 duplicates: 0 warnings: 0
unique 约束创建完毕后,外键创建成功。
mysql> alter table test_sub2
-> add constraint main_id_cons2
-> foreign key (main_id)
-> references test_main2(id);
query ok, 2 rows affected (0.14 sec)
records: 2 duplicates: 0 warnings: 0
我要举报
如以上问答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯