2015-11-21 96 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

你需要DeptPRIMARY KEYUNIQUE爲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) 
);