SQL

时间:2018-03-31 05:40:52

标签: sql

考虑到这四种关系:

Mentorship (mentee_id, mentor_id)
Study (sid, credits)
Enrollment (did, sid)
Student (sid, street , city )

我想写一个查询,找出所有与他们的导师住在同一城市和街道的学生,假设所有导师和学员都是学生。

我尝试将此查询编写为:

SELECT sid
FROM Student, Mentorship
WHERE street IN (SELECT sid
                 FROM Student, Mentorship
                 WHERE mentor_sid = sid 
                   AND ...   )

它不完整但我试图从学生和导师关系中选择一个sid,其中街道陷入mentor_sidmentee_sid具有相同街道和城市的状态。

我是SQL的新手,仍然对如何做这些事情感到困惑。

1 个答案:

答案 0 :(得分:1)

您需要通过链接表

将学生(被指导者)加入学生(导师)
SELECT s1.* FROM Student s1
INNER JOIN Mentorship m ON s1.sid = m.mentee_id
INNER JOIN student s2 ON s2.sid = m.mentor_id 
   AND s2.street = s1.street AND s2.city = s1.city