SQL外键帮助。 ORA-00907缺少右括号

时间:2019-01-21 05:27:47

标签: sql oracle

我是SQL的新手,我在CourseEnrollments表中的外键上遇到了麻烦。

我一直收到错误报告- ORA-00907:缺少右括号 00907. 00000-“缺少右括号 *原因: *动作:

似乎所有逗号和括号都已到位。

Create Table Students 
(
StudentID INT NOT NULL,
Lastname VARCHAR2(25),
Firstname VARCHAR2(20),
Email VARCHAR2(40),
Enrollmentdate DATE,
CONSTRAINT student_pk PRIMARY KEY (StudentID)
);

/* This is the creation of the Students table */

Create Table Faculty 
(
FacultyID INT NOT NULL,
Lastname VARCHAR2(25),
Firstname VARCHAR2(20),
Email VARCHAR2(40),
Hiredate DATE,
CONSTRAINT faculty_pk PRIMARY KEY (FacultyID)
);

/* This is the creation of the Faculty table */

Create Table Courses 
(
CourseID INT NOT NULL,
"Subject (e.g. SDEV)" VARCHAR2(20),
"Catalognbr (e.g. 350)" NUMBER,
"Title (e.g. Database Security)" VARCHAR2(40),
CONSTRAINT course_pk PRIMARY KEY (CourseID)
);

/* This is the creation of the Courses table */

Create Table CourseEnrollments 
(
EnrollmentID INT NOT NULL,
  CONSTRAINT fk_Students
  FOREIGN KEY (StudentID)
  REFERENCES Students(StudentID)
CONSTRAINT fk_Faculty
  FOREIGN KEY (FacultyID)
  REFERENCES Faculty(FacultyID)
CONSTRAINT fk_Courses
  FOREIGN KEY (CourseID)
  REFERENCES Courses(CourseID)
CONSTRAINT enrollment_pk PRIMARY KEY (EnrollmentID)
);

2 个答案:

答案 0 :(得分:3)

首先应首先明确定义需要约束的列,然后才能定义约束。此外,当定义多个约束时,需要将它们用逗号分隔。 这是工作代码(其余代码已经可以了)。

Create Table CourseEnrollments 
(
EnrollmentID INT NOT NULL,
StudentID int,
FacultyID int,
CourseID int,
CONSTRAINT fk_Students
  FOREIGN KEY (StudentID)
  REFERENCES Students(StudentID),
CONSTRAINT fk_Faculty
  FOREIGN KEY (FacultyID)
  REFERENCES Faculty(FacultyID),
CONSTRAINT fk_Courses
  FOREIGN KEY (CourseID)
  REFERENCES Courses(CourseID),
CONSTRAINT enrollment_pk PRIMARY KEY (EnrollmentID)
);

答案 1 :(得分:1)

此消息

  

ORA-00907: missing right parenthesis

...始终表示语法错误。有时候,这确实意味着我们丢下了括号。通常,这意味着我们拼错了关键字或省略了元素,因此编译器会找到关键字或其他未预期的内容。

在这种情况下,您在constraints子句中省略了逗号。编译器期望表子句(列和约束声明)由逗号分隔。当一个这样的子句的结尾时,它正在寻找一个逗号。找不到期望)表示表规范末尾的逗号。相反,它找到了constraint,因此向ORA-00907投掷。