3

第一次在 Stack Overflow 上提出问题......很棒的资源,但作为 SQL 的新手,只有一件事让我非常困惑。

我有三个表,我想获取与 Bob 的学生相关的所有导师的姓名。

表 1:教师

================
ID     Name
================
1     Bob

表 2:学生

===================================
STUDENT_ID     Name     TEACHER_ID
===================================
1              Jayne    1
2              Billy    5
3              Mark     2

表 3:MENTOR_RELATIONSHIPS

==============================
ID     STUDENT_ID    MENTOR_ID
==============================
1      1             3
2      2             2
3      3             3

表 4:导师

=====================
MENTOR_ID     Name  
=====================
1            Sally
2            Gillian
3            Sean

我想运行一个查询来查找 Bob 学生的所有导师。因此,所有学生的导师TEACHER_ID = 1

在这种情况下,肖恩将是结果。

我知道这与加入有关,或者我可以使用普通查询找到它吗?

任何帮助深表感谢!非常感谢...

4

5 回答 5

9

这应该做的工作

select distinct m.name from students s
inner join mentor_ralationships mr on mr.student_id=s.student_id
inner join mentors m on m.mentoir_id=mr.mentor_id
where s.teacher_id=1;
于 2013-09-05T17:45:10.707 回答
0

没有连接(不是首选)

SELECT mentors.name FROM mentors 
WHERE mentors.id 
  IN (SELECT MENTOR_RELATIONSHIPS.mentor FROM  MENTOR_RELATIONSHIPS 
  WHERE  MENTOR_RELATIONSHIPS.student 
    IN (SELECT students.id FROM students WHERE students.teacher 
        = (SELECT teachers.id FROM teachers WHERE teachers.name = 'bob')));
于 2018-06-15T03:27:42.133 回答
0

这可能对您有所帮助,因为AssignedSubject, Section and SchoolClass当老师分配给特定主题时,我必须从三个表中检索数据,然后我必须找出他的班级和部分详细信息,包括我这样做的 subjectid

select a.StaffID, a.SubjectID, s.ID as SectionId, s.Name as SectionName, S.Remarks as SectionRemarks, sc.ID as ClassId, sc.Name as ClassName, sc.Remarks as ClassRemarks from AssignedSubject a
     inner join Section s on a.SectionId=s.ID 
     inner join SchoolClass sc on sc.ID=s.ClassId  where a.StaffID=3068
于 2018-12-08T12:40:50.423 回答
-1
SELECT TEACHER.NAME, STUDENTS.NAME AS STUDENT NAME, MENTORS.NAME AS MENTOR 
FROM TEACHERS JOIN STUDENTS ON TEACHERS.ID = STUDENTS.TEACHER_ID 
              JOIN MENTOR_RELATIONSHIPS ON STUDENTS.STUDENT_ID = 
                   MENTOR_RELATIONSHIPS.STUDENT_ID 
              JOIN MENTORS ON MENTOR_RELATIONSHIPS.MENTOR_ID = MENTORS.MENTOR_ID 
WHERE TEACHER.NAME = 'Bob' ;
于 2018-02-27T00:43:46.663 回答
-1

您可以尝试以下方法:

SELECT DISTINCT m.name
FROM students s INNER JOIN TEACHERS t ON t.ID = a.TEACHER_ID
  INNER JOIN MENTOR_RELATIONSHIPS mr ON mr.Student_id = s.Student_id
  INNER JOIN Mentors m ON mr.MENTOR_ID = s.MENTOR_ID
WHERE s.teacher_id = 1   WHERE t.Name = 'Bob';
于 2016-12-08T09:58:25.510 回答