資料庫notexist
『壹』 資料庫語言關於not exist的用法
鹵煮你好,
答案寫法很好,我看了很久才弄明白,但我認為有漏洞,實際應用的話應該需要完善
我先說我的寫法,再解釋答案的邏輯
我的:
select st.sno, st.sname
FROM student st
where exists(
select 1 from SC a join Cource b on a.Cno=b.Cno where a.Sno=st.Sno and
a.Cno in(3,5,8) having count(*)=3
)
或者
select st.sno, st.sname
FROM student st
where exists(
select 1 from SC where Sno=st.Sno and
Cno in(3,5,8) having count(*)=3
)
/*通過和上面的比較你可以發現其實Cource其實沒有作用,但是第一種寫法更加嚴密,因為可以判斷SC中的Cno是不是有效的*/
-------分割線--------------------------
再來看看這個答案
SELECT student.sno, student.sname
FROM student
WHERE not exists(select course.cno
from course
where course.cno in (3,5,8) and not exists(select *
from sc
where student.sno=sc.sno and course.cno=sc.cno));
看起來很復雜,我們先來拆分下
因為sql 的查詢和執行是逐條進行的,主體是從Student表中中選數據,我們假設Student中有【小明】這個人,如何判斷小明是不是該出來呢,只要
select course.cno
from course
where course.cno in (3,5,8) and not exists(select *
from sc
where 『小明』=sc.sno and course.cno=sc.cno)
這一大坨【不返回結果】即可,
這一坨
,select course.cno
from course
where course.cno in (3,5,8) and not exists(select *
from sc
where 『小明』=sc.sno and course.cno=sc.cno)
意思就比較明確了(我這兒迷糊了好一陣子)
只要小明同時選修了3,5,8那麼這段話就不返回結果,所以最終小明就出現了!
/*ps.題目有個地方我沒太看明白,「3且5且8」 是指的是同時選修3,5,8呢還是同時選修3,5,8且只選修這三個。如果是後者這3個寫法還要再加一句exists*/
----三段寫法全部測試通過,鹵煮可以盡情測試~要給分啊!!!!!!!!!!!!
『貳』 mysql資料庫,not exists 語句
在sql語言里"存在"exists子句是非常不好理解的。
exists子句有兩種用法,一種為獨立exists子查詢,另一種是父子關聯子查詢。前者對父查詢不構成篩選作用,子查詢若果有記錄存在的話則輸出所有的父查詢記錄集,反之則父查詢輸出空記錄集。後者會對父查詢構成篩選作用,不使用not關鍵字的情況下輸出父查詢中與子查詢的交集,而使用not時則輸出父查詢中與子查詢的非交集。至於如何判斷exists子查詢屬於獨立還是父子關聯查詢,以及為什麼父子關聯exists子查詢會對父查詢構成篩選作用,解釋起來需要很大的篇幅這里就不講了。反正我們記住父子關聯查詢的最常用功能就是它可以求出兩張表的交集或非交集(使用not關鍵字)和不使用group分組的情況下求出某張表的最大值或最小值。
現在回到題主的具體問題上,這個問題涉及到三張表,學生表student、選課表sc、課程表course。
提問要求列出選取了所有課程的學生名單。
下面是提問中給出的sql語句:
select sname from student
where not exists(
select * from course
where not exists(
select * from sc
where sno=student.sno
and cno=course.cno));
從該語句我們看到它使用了兩個嵌套父子關聯不存在判斷not exists子句,顯然是要通過求非交集的方法查出選修了所有課程的學生名單。
一個學生如果他至少有一門課程沒有選修,那麼他在課程表裡就會存在與選課表的非交集,我們姑且稱之為「未選所有課程學生名單子集」,它由內層的not exists選出
...
select * from course
where not exists(
select * from sc
sno=student.sno
and cno=course.cno) .
『叄』 sql中 not exists的問題
那你這個查詢結果應該是為空。
not exists 的用法是 沒有返回結果 為真。
EXCEPT是指在第一個集合中存在,但是不存在於第二個集合中的數據。
你A系有沒有被學生選擇的課程。也就是說not exists是有返回值的。有返回值那表示1=0 所以為空
『肆』 怎麼理解資料庫中not exist
not exists 是取反邏輯,也就是裡面查詢沒有結果集就是為真,如果有結果集就是為假。然後作為整體的條件拼接到著查詢上
『伍』 sql中not exists用法
恩,對的,其實寫法很多
1、
select id from a where id not in (select id_no from b)
2、
select id from a
except
select id_no from b
『陸』 關於sql語句 (not exists)
not exits{ 是信息系 not exits(參加項目) }
為什麼是 信息系參加項目的
-- 不存在(是信息系 不存在(參加項目))
選出 不是信息系裡且不參加項目的人
選出 除過信息系裡參加項目的人和其他系的什麼什麼
『柒』 資料庫語言 not exists 是什麼意思
就是不在這個范圍的意思
select id
from table
where name not exists(select 1
from table
where name = 'aaa')
也許你看不懂這個1的意思,不過在使用EXISTS的時候,通常都會使用1,它代表所查詢出來的集合,等同於select name。
整個例子的意思是:查詢name不等於aaa的所有ID。
不明白再問我,謝謝!