【问题标题】:Resolving table(mysql, php)解析表(mysql,php)
【发布时间】:2016-04-06 01:53:22
【问题描述】:

我有 3 个表,分别称为 class 、 student 和 class_student(resolving table) 。这是由于班级和学生之间的多对多关系造成的。一个学生可以有很多班级,一个班级可以有很多学生。类里面的字段是(class_id, class_start_time and class_end_time), student(student_id, student_name, student_age), class_student(student_id, class_id)。我的问题是:在一个班级内,它包括学生,我如何将学生添加到班级表中?还是我应该使用解析表?我对解析表的理解很薄弱,我不确定它的目的是什么。

谢谢大家的回答!

当我向班级学生表添加新记录时,我是否也向班级表添加新记录?

【问题讨论】:

  • 在您的示例中使用 class_student 这种表是完全正常的。当您需要多对多关系时。你可以继续。
  • "how do I add student into the class table" - 嗯,你没有。您使用它们之间的表连接记录,正如您所描述的那样。有什么问题?
  • 我认为更常用的术语是关系表
  • 创建学生时,您会在学生表中添加一行。当您将学生添加到班级时,您会在 class_student 表中添加一个新行(class_id 和 student_id)。这样您就可以列出与该课程相关的所有学生
  • 当我将一个学生添加到 class 时,将为 class_student 表添加一个新行。是不是意味着类也会增加一个新行?

标签: php mysql


【解决方案1】:

您不会在班级表中添加学生。如果您这样做,那么首先将班级与学生分开是没有意义的(您已经防止了数据冗余)。我相信表格结构足以实现您的目标。作为学生和班级表中的主键的辅助键(student_id,class_id)分别完成这项工作。

类表

id|  title  | start | end
1   Biology    8am    10am
2   English    10am   12pm

学生桌

id | name |
1    John
2    Doe

学生班级表

student_id  | class_id
1               1
1               2
2               1

从桌子上,我可以

  1. 获取 John(user.id: 1) 注册的所有课程

    SELECT FROM student_class WHERE student.student_id  = '1'
    
  2. 所有注册生物学的学生(class.id:1)

    SELECT FROM student_class WHERE student.class_id  = '1'
    

    注意我知道您需要在结果中显示学生的姓名。 非常简单,只需在 student_class.class_id = student.id 上使用 student_class 表“左连接”类表

然后,对于您从 student_class 表中获得的每条记录,“名称”(或您选择包含在结果集中的其他列)将从类表中添加。

注意你刚刚加入class表的方式,你可以对student表做同样的事情。例如,您希望学生打印他们注册的课程的时间表,您仍然可以从student_class 表中选择并使用LEFT JOIN 获取startend 时间

【讨论】:

  • 插入语句怎么样?当我向 class_student table 添加新记录时,我还需要为 class 添加新记录。我该怎么做?
【解决方案2】:

解决多对多关系的最常见方法是通过单独的relation table(如 Barmar 所述)。

在您的情况下,该表可能包含以下字段:

table class_students
--------------------
id      // an unique id of that relationship; 
        // could be ommitted, could be an autoincrement, 
        // could also be a "handcrafted" id like classid_userid -> 21_13 (I need this kind of id's for an ember-api. 
        // All depending on your needs
class   // the id of the related class
student   // the id of the related student
// maybe add additional fields:
type     // to describe that relationship
sort     

然后你会得到一个特定班级的所有学生,如下所示:

$class_id = 1;
$sql = "Select * from students, class_students where students.id=class_students.student AND class_student.class=".$class_id;
// note, that you should do that via prepared statements, 
// this is only for simplicity to show how to proceed.

【讨论】:

  • 插入语句怎么样?我是否只将学生插入 class_student 表?课桌呢?
猜你喜欢
  • 1970-01-01
  • 2022-11-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-02
  • 2012-11-01
  • 2015-08-23
  • 1970-01-01
相关资源
最近更新 更多