2015-12-11 46 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