从模式创建 table 复合键

Creating a table composite key from schema

GCD needs a new database created to store all the necessary information about
their students, programmes, modules, and corresponding grade per module. The
detail is as follows:

– The college keeps track of each student’s name, student number, social security
number, address, phone, date-of-birth, and gender.

– Each programme is described by a programme code, name, description, duration
(number of years), level, and the cost.

– Each module has a module code, name, description, duration (number of weeks),
level (introductory, intermediate, advance).

– Grade stores student number, module code, and a letter grade (A, B, C, D, E, F).

Each programme enrolls students. Students then register modules. At the end of the
study duration of a module students receive their grades.

因为这是一个复合键,我怎么能从中创建一个 table?

(sNumber, mCode, grade)

我正在这样尝试

Grade
CREATE TABLE grade (
sNumber INT NOT NULL,
mCode INT NOT NULL,
grade CHAR (1),
PRIMARY KEY(sNumber, mCode)
);

如果我更改某个模块的 mCode,结合一些命令会更好吗?

ON DELETE SET NULL & ON UPDATE CASCADE

As this is a composite key how could I create a table from this?
(SQL for CREATE TABLE)

这将不起作用,因为语法不正确。直接 RTFM 问题。

  • 当你这样使用 PRIMARY KEY 时,它指的是单个列。

  • 对于多列,在列之后、右括号之前使用 CONSTRAINT 关键字。使用有意义的约束名称(这将有助于您在管理任务期间查看列表)。

  • 同样适用于复合FOREIGN KEY

我将使用我对您 的回答中的 StudentGrade table。

CREATE TABLE student_grade (
    programme_code CHAR(6) NOT NULL,
    module_code    CHAR(8) NOT NULL,
    student_no     BIGINT  NOT NULL,
    grade          CHAR(1) NOT NULL,
    CONSTRAINT pk
        PRIMARY KEY ( programme_code, module_code, student_no ),
    CONSTRAINT student_module_achieves_student_grade
        FOREIGN KEY               ( programme_code, module_code, student_no )
        REFERENCES student_module ( programme_code, module_code, student_no ),
    CONSTRAINT grade_ranks_student_grade
        FOREIGN KEY       ( grade )
        REFERENCES grade  ( grade )
    );

Would it be better practice to combine some commands like in case i change the mCode for a certain module?
ON UPDATE CASCADE

您必须了解它的作用:当您更新 PK 列时,套件会将更改级联到所有子行;孙子行;等等

  • 它节省了您编写一堆执行批处理 OLTP 事务的过程,到级联 DELETE 到所有后代 tables。

  • 在使用正版 SQL 平台的 OLTP 系统中将被禁止。

  • 对于MySQL,这不是SQL,没有OLTP的机会(没有ACID事务;没有过程;没有服务器架构),那很好,它是小型免费软件系统的替代品。

ON DELETE SET NULL

理解。这样做的目的是,对于具有 FK 的子行,当父行(在父 table 中是 PK)被删除时,它将子行中的 FK 设置为 NULL。

  • 同样,这是非常糟糕的做法,在 OLTP 系统中被禁止,但在 MySQL 等免费软件套件中很好并且很常见,因为它没有 SQL 或事务或批处理功能。

  • 分开点。当你有一个关系数据库,比如我给你的数据模型,它是一个 'tight' 数据库:它有关系完整性;等等,你真的不想那样做。当删除具有后代的父项时,您希望停止(错误消息)。

  • 系统准备就绪并填充数据库后,想象一下遇到 ModuleCode 的 FK 为 NULL 的 StudentGrade。
    没有.

  • JOIN 将失败,并且这些行将不再出现在相关报告中(它们应该出现并且预计会出现)。
    没有.

而且你肯定也不想要这个: ON DELETE CASCADE 因为您将丢失所有后代行。 没有.