2017-02-11 156 views
0

我有這兩個表格: 先決條件:(cid,pre-cid) (記錄:sid,cid,qtr,year,grade)。SQL:找到完成課程的學生prerequsite

我必須找到那些只使用NOT IN來滿足某個班級的先決條件的學生。我當前的查詢是:

select distinct sid 
from record 
where sid not in (
     select s.sid 
     from record s, 
      prerequisite p 
     where p.cid = "CSE132X" 
      and s.cid <> p.precid 
      and s.grade < 2 
     ); 

但是,我的查詢返回已採取任何先決條件,而不是所有先決條件的學生。我很難弄清楚如何製作,以便檢查課程的所有先決條件。

+0

採樣數據與預期的結果集一起將有助於澄清你實際上是試圖實現。 –

回答

1
select distinct r.sid 
from record r 
where r.sid not in (
    select r.sid 
    from prerequisite c 
    where c.cid = "CSE132X" and 
    c.pre-cid not in (
      select r2.cid 
      from record r2 
      where r2.sid = r.sid 
    ) 
); 
+0

是的,我知道我需要兩個嵌套查詢,但是很難處理每個嵌套查詢的內容。我現在明白我應該在嵌套查詢中做一個pre-cid。謝謝! –

+0

@ L.S。 「X = not not X」邏輯可以用英語表示爲「已採取所有先決條件=沒有未採取的先決條件」。 –

0

事情是這樣的:

select distinct sid from record y where grade>=2 and not exists(select * from prerequisite where cid='CSE132X' and precid not in (select cid from record x where x.sid=y.sid));

+0

謝謝,我能夠將它變成只使用NOT IN的查詢並生成正確的輸出: 從記錄y中選擇不同的y.sid,其中y.grade> = 2且y.sid不在 (select s .sid from record s,prerequisite p where p.cid =「CSE132X」 and p.precid not in(select x.cid from record x where x.sid = y.sid)); –