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
如何编写查询以从所有表中获取学生S1的信息。 例如,学生S1参加体育名称,教学生S1的教师姓名,学生S1父母信息。这里学生,老师,父表中的id是主键。 stud_id,teacher_id,sports_id是指学生,教师,体育表主键的外键。 请帮我从表中获取学生S1的记录。提前致谢。
答案 0 :(得分:1)
以下是解决方案:
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;
答案 1 :(得分:1)
您可以简单地使用where子句:
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
答案 2 :(得分:0)
您需要合并student_teacher
和student_sports
表。没有办法嫁给哪位老师教某个学生参加某项运动。我们所知道的是学生1参加了第1,2和3项运动,并由老师1,2和3教授。我们不知道哪位老师参加了哪项运动。你应该这样:
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
答案 3 :(得分:0)
您可以使用内部联接
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;