我不知道我的错误在'关键字CONSTRAINT附近的语法不正确'

时间:2015-01-29 22:39:03

标签: mysql sql

CREATE TABLE ClassRegistration(
StudentID int   NOT NULL,
CourseID int    NOT NULL,

CONSTRAINT PK_ClassRegistration PRIMARY KEY (StudentID, CourseID),
CONSTRAINT FK_ClassRegistration_Students,
FOREIGN KEY(StudentID) REFERENCES Students(ID),
ON DELETE CASCADE ON UPDATE CASCADE,

CONSTRAINT FK_ClassRegistration_Classes,
FOREIGN KEY(CourseID) REFERENCES Course(ClassNumber),
ON DELETE CASCADE ON UPDATE CASCADE
)

我认为这只是一个问题,在哪里放逗号,但我在教自己,所以很难弄清楚这一点。

3 个答案:

答案 0 :(得分:2)

约束定义没有" embedded"逗号:

CREATE TABLE ClassRegistration
(
   StudentID int   NOT NULL,
   CourseID int    NOT NULL,

   CONSTRAINT PK_ClassRegistration PRIMARY KEY (StudentID, CourseID),

   CONSTRAINT FK_ClassRegistration_Students   --- no comma here
   FOREIGN KEY(StudentID) REFERENCES Students(ID) -- no comma here
   ON DELETE CASCADE ON UPDATE CASCADE,

   CONSTRAINT FK_ClassRegistration_Classes -- no comma here
   FOREIGN KEY(CourseID) REFERENCES Course(ClassNumber) -- no comma here
   ON DELETE CASCADE ON UPDATE CASCADE
);

顺便说一下:CONSTRAINT PK_ClassRegistration部分没用。您不能在MySQL中为主键约束指定名称(您可以指定它,但它会被忽略并始终命名为PRIMARY

答案 1 :(得分:1)

你添加太多逗号,

CREATE TABLE ClassRegistration(
StudentID int   NOT NULL,
CourseID int    NOT NULL,

CONSTRAINT PK_ClassRegistration PRIMARY KEY (StudentID, CourseID),
CONSTRAINT FK_ClassRegistration_Students
FOREIGN KEY(StudentID) REFERENCES Students(ID)
ON DELETE CASCADE ON UPDATE CASCADE,

CONSTRAINT FK_ClassRegistration_Classes
FOREIGN KEY(CourseID) REFERENCES Course(ClassNumber)
ON DELETE CASCADE ON UPDATE CASCADE
);

有关正确语法的信息,请参阅此处。

http://dev.mysql.com/doc/refman/5.1/en/create-table.html

答案 2 :(得分:1)

CREATE TABLE ClassRegistration(
    StudentID int   NOT NULL,
    CourseID int    NOT NULL,

    PRIMARY KEY (StudentID, CourseID),

    CONSTRAINT FK_ClassRegistration_Classes
    FOREIGN KEY(StudentID) REFERENCES Students(ID) ON DELETE CASCADE ON UPDATE CASCADE,

    CONSTRAINT FK_ClassRegistration_Classes
    FOREIGN KEY(CourseID) REFERENCES Course(ClassNumber) ON DELETE CASCADE ON UPDATE CASCADE
)