【正文】
FROM C WHERE Cname=‘DB’));聯(lián)接查詢方式(2)帶有比較運算符的子查詢例30:查詢與“張三”在同一個系學習的學生學號、姓名和系別。 SELECT Sno,Sname,Sdept FROM S WHERE Sdept = (SELECT Sdept FROM S WHERE Sname=‘張三’);例31:查詢選修課程名為“數(shù)據(jù)庫”的學生學號和姓名。 SELECT Sno,Sname FROM S WHERE Sno IN (SELECT Sno FROM SC WHERE Cno = (SELECT Cno FROM C WHERE Cname=‘DB’));(3)帶有EXISTS謂詞的子查詢(1)帶有EXISTS謂詞的子查詢不返回任何實際數(shù)據(jù),它只產(chǎn)生邏輯值。例32:查詢選修了C2課程的學生姓名。 Sname FROM S WHERE Sno IN ( SELECT Sno FROM SC WHERE Cno=‘C2’)。 Sname FROM S WHERE EXISTS ( SELECT * FROM SC WHERE = AND Cno=‘C2’)。 例33:查詢所有未選修C2課程的學生姓名。 SELECT Sname FROM S WHERE NOT EXISTS ( SELECT * FROM SC WHERE = AND Cno=‘C2’)。 [NOT]EXISTS 實際上是一種內(nèi)、外層互相關(guān)的嵌套查詢,只有當內(nèi)層引用了外層的值,這種查詢才有意義。例34:查詢與“張三”在同一個系學習的學生學號、姓名和系別。 SELECT Sno,Sname,Sdept FROM S AS S1 WHERE EXISTS (SELECT * FROM S AS S2WHERE =S1. Sdept AND =‘張三’);相關(guān)子查詢例35:查詢選修了全部課程的學生姓名。在表S中找學生,要求這個學生學了全部課程。換言之,在S表中找學生,在C中不存在一門課程,這個學生沒有學。 SELECT Sname FROM S WHERE NOT EXISTS (SELECT * FROM C WHERE NOT EXISTS (SELECT * FROM SC WHERE = AND =));例36:查詢所學課程包含學生S3所學課程的學生學號分析:不存在這樣的課程Y,學生S3選了Y,而其他學生沒有選。SELECT DISTINCT Sno FROM SC AS X WHERE NOT EXISTS (SELECT * FROM SC AS Y WHERE =‘S3’ AND NOT EXISTS (SELECT * FROM SC AS Z WHERE = AND =));