postgresql psql中的外键顺序(数据库规范化)

cwxwcias  于 2022-12-23  发布在  PostgreSQL
关注(0)|答案(1)|浏览(132)

学生数据库,必须规范化3NF并放入PSQL中,我不知道为了保持FK的引用完整性,应该以什么顺序插入表中
属性:

  • 学号
  • 姓名
  • 电子邮件
  • 入组年份
  • 教师
  • 课程名称
  • 课程编号
  • 专业
  • 学年
  • 学期标签(学期/年份)
  • 等级

这些是我创建的表,我知道我搞砸了学生表,可能还有学期表......或者我只是不知道如何正确地连接。我需要它们都以允许f键转移到正确表的顺序连接,但我无法理解它

CREATE TABLE STUDENT (       
STUDENT_ID SERIAL PRIMARY KEY,
STUDENT_NUMBER CHAR(15) NOT NULL UNIQUE,
NAME VARCHAR(40) NOT NULL,
EMAIL VARCHAR(30) UNIQUE
);

CREATE TABLE SEMESTERS (
SEMESTER_ID SERIAL PRIMARY KEY,
SEMESTER_LABEL CHAR(10),
ACADEMIC_YEAR CHAR(6),
TERM CHAR(6)
);

CREATE TABLE DEPARTMENTS (
DEPARTMENT_ID SERIAL PRIMARY KEY,
DEPARTMENT CHAR(6),
);

CREATE TABLE COURSE_NAMES (
COURSE_NAME_ID SERIAL PRIMARY KEY,
COURSE_NAME TEXT,
DEPARTMENT_ID INTEGER NOT NULL REFERENCES DEPARTMENTS(DEPARTMENT_ID),
SEMESTER_ID INTEGER NOT NULL REFERENCES SEMESTERS(SEMESTER_ID)
);

CREATE TABLE COURSES (
COURSE_ID SERIAL PRIMARY KEY,
COURSE_NUMBER CHAR(6),
SEMESTER_ID INTEGER NOT NULL REFERENCES SEMESTERS(SEMESTER_ID),
COURSE_NAME_ID INTEGER NOT NULL REFERENCES COURSE_NAMES(COURSE_NAME_ID)
);

CREATE TABLE TEACHERS (
TEACHER_ID SERIAL PRIMARY KEY,
TEACHER_NAME VARCHAR(40) NOT NULL,
DEPARTMENT_ID INTEGER REFERENCES DEPARTMENTS(DEPARTMENT_ID)
);

CREATE TABLE CLASS (
CLASS_ID SERIAL PRIMARY KEY,
COURSE_ID INTEGER NOT NULL REFERENCES COURSES(COURSE_ID),
TEACHER_ID INTEGER NOT NULL REFERENCES TEACHERS(TEACHER_ID),
SEMESTER_ID INTEGER NOT NULL REFERENCES SEMESTERS(SEMESTER_ID)
);

CREATE TABLE CLASS_SCHEDULE (
CLASS_SCHEDULE_ID SERIAL PRIMARY KEY,
CLASS_ID INTEGER NOT NULL REFERENCES CLASS(CLASS_ID),
STUDENT_ID INTEGER NOT NULL REFERENCES STUDENT(STUDENT_ID)
);

CREATE TABLE REGISTRATION (
REGISTRATION_ID SERIAL PRIMARY KEY,
CLASS_ID INTEGER NOT NULL REFERENCES CLASS(CLASS_ID),
STUDENT_ID INTEGER NOT NULL REFERENCES STUDENT(STUDENT_ID),
YEAR ENROLLED CHAR(6)
);

CREATE TABLE ACADEMIC_RECORDS (
ACADEMIC_RECORD_ID SERIAL PRIMARY KEY,
STUDENT_ID INTEGER NOT NULL REFERENCES STUDENT(STUDENT_ID),
REGISTRATION_ID INTEGER NOT NULL REFERENCES REGISTRATION(REGISTRATION_ID),
GRADE DECIMAL(16,15)
);

CREATE TABLE MAJORS (
MAJOR_ID SERIAL PRIMARY KEY,
SEMESTER_ID INTEGER NOT NULL REFERENCES SEMESTERS(SEMESTER_ID)
);

CREATE TABLE MAJOR_DECLARATION (
MAJOR_DEC_ID SERIAL PRIMARY KEY,
MAJOR_ID INTEGER NOT NULL REFERENCES MAJORS(MAJOR_ID),
STUDENT_ID INTEGER NOT NULL REFERENCES STUDENT(STUDENT_ID),
SEMESTER_ID INTEGER NOT NULL REFERENCES SEMESTERS(SEMESTER_ID)
);
nvbavucw

nvbavucw1#

我的建议是导入所有不带FK关系的数据,并在插入所有数据后手动设置关系。临时删除FK关系是处理这种情况的有效方法。通常,这种方法可以更快地完成工作。

相关问题