mysql學習筆記:集合運算並交差,其他


 

總結一下今天數據庫課堂上的所學2333

1.

SQL語言實踐中,集合運算的實現方法,推薦順序如下:

運算:union

運算:in, exists, intersect(很多DBMS基本上不支持ing qwq)-------->"同時"

運算:not in, not exists, except, minus

還有一種運算我在這也寫一寫哉2333,除法運算:not exists ... not exists...

2.像老師提的那樣要學會盡量一題多做,擴展思維!

看這道題:查詢選修了數據庫課程的學生學號和姓名

分析:可以用連接運算;也可以來2層嵌套查詢,3層嵌套查詢搞一波;也可以用存在量詞exists實現查詢之

參考代碼記錄如下:

select sc.sno,sname
from student,c,sc
where student.sno=sc.sno and sc.cno=c.cno and cname='數據庫';

select sno,sname from student
where sno in (select sno from sc
where cno in (select cno from c where cname='數據庫'));

select sno,sname from student
where sno in (select sno from sc,c where sc.cno=c.cno and cname='數據庫'); 

/*exists實現*/
select sno,sname from student
where exists (select * from sc,c where sc.cno=c.cno and sc.sno=student.sno and cname='數據庫'); 
/*盡量能去拓展幾種寫法,從計算效率來說,連接查詢效率大*/

  

 

 

3.討論一下集合交運算

 

 

用in實現之:

 

 

/*查詢同時選擇了1號課程和2號課程的學生的學號*/
select sno
from sc 
where cno='1' 
and sno in(	/*用in間接實現交運算*/
select sno
from sc
where cno='2');

 

  用 exists  相關子查詢實現之:

/*查詢同時選擇了1號課程和2號課程的學生的學號*/
select sno
from sc as a
where cno='1'
and exists (/*exists交運算*/
select * 
from sc as b
where cno='2'
and b.sno=a.sno);
/*exists代表存在量詞,it just returns true or false*/

  

差運算也是很相似的,接下來:求選修了1號課程但沒有選修2號課程的學生學號

用 not in 實現:

/*查詢選擇了1號課程但沒有選擇2號課程的學生的學號*/
select sno
from sc 
where cno='1' 
and sno not in(	/*用not in間接實現差運算*/
select sno
from sc
where cno='2');

差運算我自己還是覺得拿not in來用香呀2333,當然not exists實現也要去比較熟練的掌握之,2333!

用 not exists實現:

/*not exists實現差運算*/
/*查詢選擇了1號課程但沒有選擇2號課程的學生的學號*/
select sno
from sc as a
where cno='1' 
and not exists
(select *
from sc as b
where cno='2'
and b.sno=a.sno);
select * from sc;

3.用nort exists   not exists實現除運算,解決集合包含這樣的查詢,今天上午寫的一些代碼搬過來拉拉啦2333

/*查詢選修1號學生選修的所有課程的學生學號*/
select distinct sno from sc as a where not exists
(select * from sc as b where b.sno='1' and not exists
(select * from sc as c where c.sno=a.sno and c.cno=b.cno)); 

/*選了所有課程的學生學號*/
select sno from student  where not exists
(select * from c where not exists
(select * from sc  where sno=student.sno and cno=c.cno)); 

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM