简体   繁体   English

MySQL设计一对多?

[英]MySQL design one-to-many?

I have a database that deals with students. 我有一个与学生打交道的数据库。 So I have table Students and Classes. 所以我有表学生和课程。 Now every Student can go to as many classes as s/he wants; 现在,每个学生都可以按照自己的意愿去上课; how would I model this in a MySQL database schema? 我将如何在MySQL数据库模式中对此进行建模?

Students table: 学生表:

student_id
student_name
student_age
...

Classes table: 类表:

class_id
class_name
class_profesor
...

Basically I don't know how to design a table where one student could register him- or herself for as many classes as s/he wants? 基本上我不知道如何设计一个表,一个学生可以按照他/她想要的课程注册他或她自己?

Should I make another table for this? 我应该为此制作另一张桌子吗?
Is this a one-to-many relation? 这是一对多的关系吗?

You need a many-to-many or mapping table, eg: 您需要一个多对多或映射表,例如:

class_student
-------------
class_id
student_id

Primary key for this table should be: (class_id, student_id) . 该表的主键应为: (class_id, student_id)
Create an index on: 在以下位置创建索引:
(class_id, student_id) , and (class_id, student_id) ,和
(student_id, class_id) . (student_id, class_id)
Take a gander at this other SO question and answers for more detail. 深入了解其他SO问题和答案以获取更多细节。


Once you've got that set up, you can query for enrollees to a given class with: 完成设置后,您可以使用以下命令查询给定类的登记者:

SELECT c.class_name, s.student_name, ...
FROM   class_student cs
       LEFT JOIN class c   ON c.class_id = cs.class_id
       LEFT JOIN student s ON s.student_id = cs.student_id
WHERE  cs.class_id = '<some_class_id_here>'

您可以再维护一个表'Goes_to',它只存储student_id和class_id。这将规范您的数据,并且您可以根据您的要求编写不同类型的查询。

Agree with Bernie, this is a Many to Many relationship. 同意伯尼,这是一个多对多的关系。 In addition to what Bernie explained, you can add extra fields to 'class_student' table, like for example student's average grade on that class, or how many times he didn't went to that class. 除了Bernie解释的内容之外,您还可以在“class_student”表中添加额外的字段,例如学生在该课程中的平均成绩,或者他没有去过该课程的次数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM