java 如何创建带外键的表POSTGRESQL

ylamdve6  于 2023-02-07  发布在  Java
关注(0)|答案(1)|浏览(102)

我想创建4个表,有外键对方。
students

CREATE TABLE students
(
  PRIMARY KEY (student_id),
  student_id SERIAL,
  student_name VARCHAR(100),
  student_age  INT,
  entry_year INT,
  graduate_year INT,
  faculty_name VARCHAR(100),
  group_id INT,
  FOREIGN KEY (group_id) REFERENCES groups(group_id)
);

groups

CREATE TABLE groups
  (
PRIMARY KEY (group_id),
group_id   SERIAL,
group_name VARCHAR(100),
  student_id INT,
FOREIGN KEY (student_id) REFERENCES students(student_id)
  );

lessons

CREATE TABLE lessons
(
  PRIMARY KEY (lesson_id),
  lesson_id  SERIAL,
  lesson_name  VARCHAR(100),
  class_number INT,
  date TIMESTAMP,
  teacher_id INT,
  group_id INT,
  FOREIGN KEY(teacher_id) REFERENCES teachers(teacher_id),
  FOREIGN KEY (group_id) REFERENCES groups(group_id)
   );

teachers

CREATE TABLE teachers
(
  PRIMARY KEY (teacher_id),
  teacher_id INT,
  teacher_name VARCHAR(100),
  position VARCHAR(100)
);

当我在Java应用程序中运行此查询时,我获得了一个创建表students的错误:

nested exception is org.postgresql.util.PSQLException: ERROR: relation "groups" does not exist

我知道为什么会抛出异常,因为我正在从表groups创建带外键的表students,而表groups尚未创建。
但我不知道如何解决它。感谢提前回应!

4c8rllxm

4c8rllxm1#

CREATE TABLE students
(
  PRIMARY KEY (student_id),
  student_id SERIAL,
  student_name VARCHAR(100),
  student_age  INT,
  entry_year INT,
  graduate_year INT,
  faculty_name VARCHAR(100),
  group_id INT,
  CONSTRAINT fk_group
    FOREIGN KEY(group_id) 
      REFERENCES groups(group_id)
);

https://www.postgresqltutorial.com/postgresql-tutorial/postgresql-foreign-key/

相关问题