2012-07-20 76 views
1

我有這樣的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); 

什麼是重寫它的另一個或最好的辦法(明顯)的學生總數。

您的幫助將被apprecaited。

+0

這個查詢有什麼問題?對我來說看起來很好:半連接(IN/EXISTS)既是訪問數據的有效方式,也是傳達意義的好方法。 – 2012-07-20 09:28:14

+0

我想重寫它的另一種有效避免子查詢的方式。 – jamesT 2012-07-20 09:35:05

+0

如果這是一個性能問題,您應該提供解釋計劃,實際查詢時間和預期查詢時間以及任何索引,所有表結構和數據量。 – 2012-07-20 09:42:05

回答

3

爲什麼不使用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 
+0

感謝您的回答。 – jamesT 2012-07-20 09:35:27

0
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) 

使用EXISTS,因爲這隻要它已經評估返回一個true/false,以外部查詢。

+0

感謝您的回答。 – jamesT 2012-07-20 09:35:41

相關問題