Mysql 如何以更好的方式重写此嵌套查询?

Mysql 如何以更好的方式重写此嵌套查询?,mysql,sql,oracle,Mysql,Sql,Oracle,我有一个sql,它可以找到参加ID为10101的讲师教授的课程部分的(不同的)学生总数 select count (distinct ID) from takes where (course_id, sec_id, semester, year) in (select course_id, sec_id, semester, year from teaches

我有一个sql,它可以找到参加ID为10101的讲师教授的课程部分的(不同的)学生总数

            select count (distinct ID)
            from takes
            where (course_id, sec_id, semester, year) in 
            (select course_id, sec_id, semester, year
            from teaches
            where teaches.ID= 10101);
重写它的另一种或最好的方法是什么

我们将感谢你的帮助

select count (distinct ta.id)
from takes ta
where EXISTS
(select 1 from teaches te
where te.ID=10101
and te.course_id=ta.course_id
and te.sec_id=ta.sec_id
and te.semester=ta.semester 
and te.year=ta.year)

存在Use,因为这会在外部查询求值后立即将布尔值true/false返回给外部查询

为什么不使用ANSI Join

select 
    count (distinct t1.ID) 
from 
    takes as t1
    inner join teaches as t2 on 
        t1.course_id=t2.course_id and
    t1.sec_id=t2.sec_id and
    t1.semester=t2.semester and
    t1.year=t2.year 
where 
    t2.ID= 10101

这个查询有什么问题?在我看来这很好:半连接(IN/EXISTS)既是访问数据的有效方式,也是传达意义的好方式。我想用另一种方式重写它,这种方式可以有效避免子查询。如果这是一个性能问题,您应该提供解释计划、实际查询时间和预期查询时间以及任何索引,所有表结构和数据量。如果不使用半联接(IN/EXISTS),就没有更好的方法获得该结果。它比所有的备选方案更有效,更容易阅读/理解。如果确定更好的查询的奇怪原则是“不要使用嵌套查询”,那么Madhivanan向您建议了正确的答案,但使用常规术语并不总是正确的。