Mysql 如何从表中检索学生信息?
如何编写查询以从所有表中获取学生S1的信息。 例如,学生S1参加体育活动的姓名、教师姓名谁教学生S1、学生S1家长信息。在这里,学生、教师、家长表中的id是主键。stud_id、teacher_id、sports_id是外键,指学生、教师、运动表主键。Mysql 如何从表中检索学生信息?,mysql,sql,join,Mysql,Sql,Join,如何编写查询以从所有表中获取学生S1的信息。 例如,学生S1参加体育活动的姓名、教师姓名谁教学生S1、学生S1家长信息。在这里,学生、教师、家长表中的id是主键。stud_id、teacher_id、sports_id是外键,指学生、教师、运动表主键。 请帮助我从表格中获取学生S1的记录。提前谢谢 以下是解决方案: student table teacher table sports table parents table --------- -------------
请帮助我从表格中获取学生S1的记录。提前谢谢 以下是解决方案:
student table teacher table sports table parents table
--------- -------------- ------------ ---------------
id name id name id name id stud_id fathername mothername
------------ ------------ ------------ -----------------------------------------
1 S1 1 T1 1 SP1 1 1 xxxxxx yyyyyyy
2 S2 2 T2 2 SP2 2 2 abc aaa
3 S3 3 T3 3 SP3
student_teacher table student_sports table
id stud_id teacher_id id sutd_id sports_id
------------------------------ ------------------------------
1 1 1 1 1 1
2 1 2 2 1 2
3 1 3 3 1 3
4 2 2 4 3 2
5 2 3 5 3 3
您可以简单地使用where子句:
select st.name as Student, t.name as teacher, sp.name as sports, p.fathername,p.mothername from student st,teacher t,sports sp,parents p,student_teacher s_t,student_sports s_s where s_t.stud_id=st.id and s_t.teacher_id=t.id and p.stud_id=st.id and s_s.stud_id=st.id;
您需要将
student\u-teacher
和student\u-sports
表组合在一起。没有办法把哪个老师教哪个学生做某项运动的结果结合起来。我们所知道的是,学生1参加了体育1、2和3,并由1、2和3老师授课。我们不知道哪位老师参加了哪项运动。你应该有这个:
select S.name, T.name, SS.name, P.fathername, P.mothername
from student S, teacher T, sports SS, parents P,student_teacher ST, student_sports SSP
where S.id = ST.stud_id and T.id = ST.teacher_id and
S.id = SSP.stud_id and SS.id = SSP.sports_id and
S.id = P.stud_id
完成后,您可以使用连接获取所有数据:
student_sports_teacher table
+----+---------+-----------+------------+
| id | stud_id | sports_id | teacher_id |
+----+---------+-----------+------------+
| 1 | 1 | 1 | 1 |
| 2 | 1 | 2 | 2 |
| 3 | 1 | 3 | 3 |
| 4 | 2 | 1 | 2 |
| 5 | 2 | 2 | 3 |
+----+---------+-----------+------------+
可以使用内部联接
SELECT * FROM student s
LEFT JOIN parents p ON s.id = p.stud_id
LEFT JOIN student_sports_teacher sst ON sst.stud_id = s.id
LEFT JOIN sports sp ON sp.id = sst.sports_id
LEFT JOIN teacher t ON t.id = sst.teacher_id
不需要使用左连接。OP使用外键,因此您不会有任何孤立记录。这只是一个习惯,我总是指定联接类型。
select st.name as Student, t.name as teacher, sp.name as sports,
p.fathername,p.mothername
from student st
Inner join student_teacher as st on st s_t.stud_id=st.id
Inner join teacher t on s_t.teacher_id=t.id
Inner join parents p on p.stud_id=st.id
Inner join student_sports ss on ss.stud_id=st.id;