【问题标题】:How to design a simple database如何设计一个简单的数据库
【发布时间】:2017-12-27 19:08:13
【问题描述】:

我想模拟学生、老师、班级的关系。每个学生都与一位老师相关联(老师可以有很多学生)。只有三个班。我认为这是三个表:

学生表 -> (student_id, student_name, class_id)

教师表 -> (student_id, student_name, class_id)

类表 -> (class_id, class_name)

我不确定如何在表格中显示师生关系。我们怎么知道哪个老师分配给哪个学生?

【问题讨论】:

  • 你再介绍一张“链接”表Student_Teacher。从StudentTeacher 中删除class_id 并将其添加到新表中。
  • 可以添加另一个表“assigned_students”并包含列:student_id、teacher_id 然后在您的代码中,只需将谁分配给谁,将其拉入/插入到该表中。
  • 这是many-to-many 关系的示例。学生可以被很多老师教,老师也可以教很多学生。您将需要一个中间表(可能是StudentTeacher)将关系分解为one-to-many

标签: mysql database


【解决方案1】:

这比您想要的要多一些表,但 Microsoft 创建的几个 .NET 示例都围绕一个类似的关系数据库。

这是该数据库的链接: https://msdn.microsoft.com/en-us/library/bb399731(v=vs.100).aspx

在这个例子中,学生和老师都保存在 person 表中,并通过两个不同的 Joining 表与 course 表相关联。 .学生成绩和课程讲师。

这是带有链接的 Contoso 大学架构: https://docs.microsoft.com/en-us/aspnet/mvc/overview/getting-started/getting-started-with-ef-using-mvc/creating-a-more-complex-data-model-for-an-asp-net-mvc-application

【讨论】:

    【解决方案2】:

    这可以通过一些简单的连接来完成。

    假设您要查找与某位老师关联的所有学生,您可以从抓住teacher 的行开始。然后,您将加入老师教的classes。最后,您将加入这些课程中的students

    这被称为多对多关系,是数据库中的一个重要概念。

    select
        t.student_name, -- I suspect this col might actually be named teacher_name
        s.student_name, 
    from
        -- Find the classes that a teacher teaches
        teacher_table t join class_table c on (t.class_id=c.class_id)
        -- Find the students in those classes
        join student_table s on (s.class_id=c.class_id)
    where
        t.student_id = ? -- Again, I suspect this should be "teacher_id"
    

    【讨论】:

    • 我要提一下,你可以直接加入teacher_table和student_table。但是我在答案中包含了类表,以证明一般可以实现多少对多。如果您不需要 classes 表中的任何数据(例如用于 where 子句的“课程完成日期”等),您可以简单地使用 SELECT t.student_name, s.student_name FROM teacher_table t JOIN student_table s ON (t.class_id=s.class_id) WHERE t.student_id = ?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-15
    • 1970-01-01
    • 1970-01-01
    • 2011-02-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多