一、sql中查詢包含關系的查詢
sql語句中包含關系可以使用 in 和exist,但有些時候僅僅用這兩個是不夠的,還有表示方法是 not exist(b expect a )可以表示a包含b。
二、這里舉一個例子
查詢中涉及2個表,一個student表,一個sc表(用來儲存每個學生的id和對應的選課id還有該學生該課的成績)
具體表的內容如下(不全):
student表: sc表:
問題:查詢至少選修了學號為“31401”的學生所選修的所有課程的學生的學號和姓名。
emmmm...
如果套用之前的公式:
1 select sno,sname 2 from student as s1 3 where not exists( 4 (select cno 5 from sc 6 where sno='31401') 7 except 8 (select sc.cno 9 from sc,student as s2 10 where sc.sno=s2.sno and s1.sname=s2.sname));
然而遺憾的是,mysql不能使用except語句,那么我們使用另一種解決方法
1 -- 找出學號為31401的同學所選課程的集合a 2 CREATE OR REPLACE VIEW a as 3 select sc.cno 4 from sc 5 where sno=31401; 6 7 -- 找出其他同學選修了集合a里的學生id和課程id的集合 8 CREATE OR REPLACE VIEW b as 9 select a.cno,sno 10 from a left join sc on a.cno=sc.cno; 11 12 -- 得出結果 13 select sno, sname 14 from student 15 where sno in(select sno 16 from b group by sno having count(distinct cno)=3);