2015-11-21 2 views
0

Я не могу понять, почему это не компиляция имеет дело с внешним ключом как-то:иностранных Ключевой вопрос SQL

Drop Table Employee; 
Drop Table Department; 


Create Table Employee(
EmpNr int not null primary key, 
EmpName Varchar(35) not null, 
Dept Varchar (2) not null, 
Gender char not null 
); 

Create Table Department(
DeptCode Varchar (2) not null primary key, 
DeptName Varchar (35) not null, 
Foreign Key (DeptCode) references Employee (Dept) 
); 

insert into Employee values (001, 'HagarT','DV','M'), 
           (002, 'WongS','DV','F'), 
           (003, 'Jones','MK','F'), 
           (004, 'MifuneK','SL','M'); 

insert into Department values ('DV', 'Development'), 
           ('MK', 'Marketing'), 
           ('RS', 'Research'),        
           ('SL', 'Sales'); 
+0

Вы можете включить сообщение об ошибке? – Martin

ответ

0

Вы должны Dept быть PRIMARY KEY или UNIQUE работать FK

Create Table Employee(
    EmpNr int not null primary key, 
    EmpName Varchar(35) not null, 
    Dept Varchar (2) unique not null, 
    Gender char not null 
); 

Как видите, ваш Employee имеет два ряда с 'DV', так что будет за границей для Department?

Я думаю, что вы хотите, это

Create Table Employee(
    EmpNr int not null primary key, 
    EmpName Varchar(35) not null, 
    Dept Varchar (2) not null, 
    Gender char not null, 
    Foreign Key (Dept) references Department (DeptCode) 
); 
Смежные вопросы