mysql无法添加2个外键

时间:2015-12-11 04:33:34

标签: php mysql sql windows

我正在为MySQL中的关联表编写脚本,并在第二个外键约束处停止编译;有谁知道什么可能是错的?拜托,我很感激!

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
);

上面的两个表格工作正常,当我把下面的表格链接到上面的两个时,有两个外键出错了

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
);

有人可以帮忙吗?

2 个答案:

答案 0 :(得分: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
);

答案 1 :(得分: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
);