我想模拟学生、老师、类(class)的关系。每个学生都与一位老师相关联(老师可以有很多学生)。只有三个类(class)。我的想法是,有三个表:
学生表 -> (student_id, student_name, class_id)
教师表 -> (student_id, student_name, class_id)
类表 -> (class_id, class_name)
我不确定如何在表格中显示师生关系。我们怎么知道哪个老师分配给了哪个学生?
最佳答案
这可以通过一些简单的连接来完成。
假设您想要查找与某位老师关联的所有学生,您可以从获取老师
的行开始。然后您将加入老师教授的类(class)
。最后,您将加入那些类(class)中的 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"
关于mysql - 如何设计一个简单的数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45242605/