更好地查询联接

时间:2010-09-22 21:32:02

标签: sql mysql query-optimization

好的,所以我有三张桌子

学生

Name        StudendId
----------------------
John            1
Jane            2
Bob             3
Betty           4

StudentId   TeacherId
----------------------
1            1
2            2
3            1
4            2
1            3
4            3

教师

Name          TeacherId
------------------------
Jim               1
Joan              2
Jill              3

好的,所以我想找到教导约翰和鲍勃的老师。

到目前为止,我的查询是,

 select distinct Teachers.Name from Teachers, 
   ((select Teachers.Name from Class, Students 
     where Students.StudendId = Class.StudentId and Students.Name = 'John') as tbl1
    join
   (select Class.TeacherId from Class, Students 
     where Students.StudendId = Class.StudentId and Students.Name = 'Bob') as tbl2
   on tbl1.TeacherId = tbl2.TeacherId) where Teachers.TeacherId = tbl1.TeacherId;

所以我想知道这是否是构建查询的最佳方式?我担心这种方法似乎不能很好地扩展,因为可能会问25名学生的普通老师。

谢谢, Vinh

2 个答案:

答案 0 :(得分:2)

使用:

  SELECT t.name
    FROM TEACHERS t
    JOIN CLASS c ON c.teacherid = t.teacherid
    JOIN STUDENTS s ON s.studentid = c.studentid
                   AND s.name IN ('John', 'Bob')
GROUP BY t.name
  HAVING COUNT(DISTINCT s.name) = 2

HAVING COUNT(DISTINCT s.name)必须等于IN子句中指定的名称数量,因为IN表示名称可以是John或Bob,除了教师同时拥有两个学生。 DISTINCT隔离了重复名称(2x约翰等)的可能性,这将是误报。

答案 1 :(得分:1)

您的查询似乎过于复杂,只需加入表格并过滤您想要的结果即可。避免不必要的内联select语句。在这种情况下,我认为分组可能比不同的更高效,但可能并不多。只要数据被正确编入索引,就不应该存在这种简单查询的扩展问题。

Select t.Name
From Teacher t
        inner join Class c on c.TeacherId = t.TeacherId
        inner join Students s1 on s1.StudentId=c.StudentId
        inner join Students s2 on s2.StudentId=c.StudentId 
Where s1.Name = 'Bob'
      and s2.Name = 'John'
Group By t.Name