2015-12-11 74 views
3

我正在爲MySQL中的關聯表編寫腳本,並停止在第二個外鍵約束下編譯;有誰知道什麼可能是錯的?請,我將不勝感激!mysql無法添加2個外鍵

create table Adviser(
    AdviserID integer not null, 
    LastName char(25) not null, 
    FirstName char(25) not null, 
    AdviserEmail varchar(100) not null, 
    OfficePhoneNumber char(12) not null, 
    constraint Adviser_pk primary key(AdviserID), 
    constraint Adviser_fk foreign key(OfficePhoneNumber) 
     references Department(OfficePhoneNumber) 
      on delete no action 
      on update no action 
); 

create table Student(
    StudentID integer not null, 
    LastName char(25) not null, 
    FirstName char(25) not null, 
    StudentEmail varchar(100) not null, 
    EnrollmentDate date not null, 
    GradDate date not null, 
    Degree char(25) not null, 
    DormPhoneNumber char(12) not null, 
    constraint Student_pk primary key(StudentID), 
    constraint Student_fk foreign key(DormPhoneNumber) 
     references Dorm(DormPhoneNumber) 
      on delete no action 
      on update no action 
); 

上方做工精細的兩個表,當我提出以下鏈接表的兩個以上不順心的事與具有2個外鍵

create table AppointmentDate1(
    AdviserID integer not null, 
    StudentID integer not null, 
    StudentAppointmentDate date not null, 
    StudentEndDate date not null, 
    constraint AppointmentDate1_pk primary key(AdviserID, StudentID), 
    constraint AppointmentDate1_fk foreign key(AdviserID) 
     references Adviser(AdviserID) 
      on delete no action 
      on update no action, 
     constraint AppointmentDate1_fk foreign key(StudentID) 
     references Student(StudentID) 
      on delete no action 
      on update no action 
); 

誰能幫助?

+0

你會得到什麼錯誤信息? –

回答

1

只需重命名兩個外鍵,它應該只是如下工作.. 我測試用在我的本地數據庫中下面的CREATE TABLE腳本,我可以成功地創建AppointmentDate1表。

create table AppointmentDate1(
    AdviserID integer not null, 
    StudentID integer not null, 
    StudentAppointmentDate date not null, 
    StudentEndDate date not null, 
    constraint AppointmentDate1_pk primary key(AdviserID, StudentID), 
    constraint AdviserId1_fk foreign key(AdviserID) 
     references Adviser(AdviserID) 
      on delete no action 
      on update no action, 
     constraint StudentId1_fk foreign key(StudentID) 
     references Student(StudentID) 
      on delete no action 
      on update no action 
); 
+0

非常感謝你的工作!這個社區很棒! – NYGJMAP

3

外鍵需要有不同的約束名稱。試試這個:

create table AppointmentDate1(
    AdviserID integer not null, 
    StudentID integer not null, 
    StudentAppointmentDate date not null, 
    StudentEndDate date not null, 
    constraint AppointmentDate1_pk primary key(AdviserID, StudentID), 
    constraint fk_AppointmentDate1_AdviserId foreign key(AdviserID) 
     references Adviser(AdviserID) 
      on delete no action 
      on update no action, 
     constraint fk_AppointmentDate1_StudentId foreign key(StudentID) 
     references Student(StudentID) 
      on delete no action 
      on update no action 
); 
+0

非常感謝你的工作!這個社區很棒! – NYGJMAP