动态表?

发布于 2024-09-25 03:41:07 字数 271 浏览 1 评论 0原文

我有一个数据库,每门课程有不同的成绩(即课程 1 的三个作业,课程 2 的两个作业,...,课程 N 和 M 作业)。就数据库设计而言,我应该如何处理这个问题?

CourseID HW1  HW2 HW3
    1    100  99  100
    2    100  75  NULL

编辑 我想我需要重新表述我的问题。截至目前,我有两个表:课程和作业。作业通过外键指向课程。我的问题是我如何知道每堂课有多少作业?

I have a database that has different grades per course (i.e. three homeworks for Course 1, two homeworks for Course 2, ... ,Course N with M homeworks). How should I handle this as far as database design goes?

CourseID HW1  HW2 HW3
    1    100  99  100
    2    100  75  NULL

EDIT
I guess I need to rephrase my question. As of right now, I have two tables, Course and Homework. Homework points to Course through a foreign key. My question is how do I know how many homeworks will be available for each class?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

贵在坚持 2024-10-02 03:41:07

不,这不是一个好的设计。这是一种反模式,我称之为元数据 Tribbles。您必须不断为每个作业添加新列,并且它们的传播会失去控制。

这是一个重复组的示例,它违反了第一范式关系数据库设计。

相反,您应该为课程创建一个表,为作业创建另一个表。作业中的每一行都引用课程中的父行。

我的问题是我如何知道每堂课有多少作业?

您可以为每个作业添加行,然后可以按如下方式对它们进行计数:

SELECT CourseId, COUNT(*) AS Num_HW_Per_Course
FROM Homeworks
GROUP BY CourseId

当然,这仅计算您用行填充表格之后的作业。所以你(或课程设计者)需要这样做。

No, this is not a good design. It's an antipattern that I called Metadata Tribbles. You have to keep adding new columns for each homework, and they propagate out of control.

It's an example of repeating groups, which violates the First Normal Form of relational database design.

Instead, you should create one table for Courses, and another table for Homeworks. Each row in Homeworks references a parent row in Courses.

My question is how do I know how many homeworks will be available for each class?

You'd add rows for each homework, then you can count them as follows:

SELECT CourseId, COUNT(*) AS Num_HW_Per_Course
FROM Homeworks
GROUP BY CourseId

Of course this only counts the homeworks after you have populated the table with rows. So you (or the course designers) need to do that.

泛滥成性 2024-10-02 03:41:07

将表分解为三个不同的表。一个保存课程,第二个保存作业,第三个将它们连接起来并存储结果。

课程:

CourseID CourseName
1        Foo

作业:

HomeworkID HomeworkName HomeworkDescription
HW1        Bar          ...

结果:

CourseID HomeworkID Result
1        HW1        100

Decompose the table into three different tables. One holds the courses, the second holds the homeworks, and the third connects them and stores the result.

Course:

CourseID CourseName
1        Foo

Homework:

HomeworkID HomeworkName HomeworkDescription
HW1        Bar          ...

Result:

CourseID HomeworkID Result
1        HW1        100
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文