我正在尝试添加外键约束,但它失败了。我之前做了很多次,我无法确定它为什么这样做。基本上,我想将Skills和Employees与Skill_Bridge表联系起来。我能够将Skills与Skill_Bridge相关联,但是当我尝试对Employees执行相同操作时,它失败了。数据类型是相同的,所以我不认为这是问题所在。我还试图为Skill_Bridge创建一个主键,然后尝试将它们联系起来并且它也不起作用。第一个约束是'FKey1'失败的约束。这是我的代码。任何帮助将不胜感激。提前谢谢。
create database if not exists Q3;
use Q3;
drop table if exists Employees;
create table Employees(
employeekey int not null,
firstName varchar (100) not null,
lastName varchar (100) not null,
employeeSkillGroupkey int not null,
primary key (employeekey) );
insert into Employees values
(1, 'Ted', 'Codd', 1),
(2, 'Ralph' ,'Kimball', 7),
(3, 'Joe' ,'Celko', 1),
(4, 'James' ,'Gosling', 2),
(5, 'Godfrey', 'Muganda', 6),
(6, 'Margy', 'Ross', 5),
(7, 'Peter', 'Chen', 4),
(8, 'Terry' ,'Halpin',3),
(9, 'Tony', 'Morgan', 2);
drop table if exists Skills;
create table Skills(
empSkillKey int not null,
empSkillDescription varchar (1000) not null,
empSkillCategory varchar (200) not null,
primary key (empSkillkey));
insert into Skills values
(1, 'SQL', 'Database'),
(2, 'ERD', 'Database'),
(3, 'DM', 'Database'),
(4, 'Java', 'Programming'),
(5, 'Pascal', 'Programming');
drop table if exists Skill_Bridge;
create table Skill_Bridge(
employeeSkillGroupkey int not null,
empSkillKey int not null
);
insert into Skill_Bridge values
( 1, 1),
( 2, 4),
( 3, 4),
( 3, 5),
( 4, 4),
( 4, 2),
( 5, 1),
( 5, 3),
( 6, 4),
( 6, 5),
( 6, 2),
( 7, 1),
( 7, 2),
( 7, 3),
( 7, 4);
ALTER TABLE Employees ADD CONSTRAINT FKey1 FOREIGN KEY (employeeSkillGroupkey)
REFERENCES Skill_Bridge (employeeSkillGroupkey)
ON DELETE Restrict
ON UPDATE Cascade;
ALTER TABLE Skill_Bridge ADD CONSTRAINT ForK2 FOREIGN KEY (empSkillKey)
REFERENCES Skills (empSkillKey)
ON DELETE Restrict
ON UPDATE Cascade;
答案 0 :(得分:0)
您需要在skill_bridge表中的employeeSkillGroupkey上创建索引,然后才能在外键中引用它,请参阅foregn keys上的mysql文档:
InnoDB允许外键引用任何索引列或组 列。但是,在引用的表中,必须有一个索引 其中引用的列被列为的第一列 同样的顺序。
您可能还想要反转外键的方向。连接表应引用主表,反之亦然。