SQL中 子查詢中運算子之間的關係

2021-05-28 15:07:31 字數 2628 閱讀 8078

在sql的子查詢中,如果子查詢返回多個行時,我們知道可以使用in關鍵字來查詢字段值屬某一組值的行,同樣,可以在查詢中使用exists、 all、 any (或some)等運算子。

其中,in()後面的子查詢是返回結果集的,換句話說執行次序和exists()不一樣,子查詢先產生結果集,然後主查詢再去結果集裡去找符合要求的字段列表去。符合要求的輸出,反之則不輸出。如:有一張bbc表,需要找出各個地區人口最大的國家:

select name,region,population from bbc

where population in

(select max(population) from bbc group by region )   order by population     

exists()後面總是個跟乙個子查詢(相關的或非相關的都行),exists的左邊不用接列名,用來測試子查詢是否返回任何結果, 他只要子查詢返回了行,exists的值就為真,其執行方式是先執行主查詢一次 再去子查詢裡查詢與其對應的結果 如果是ture則輸出,反之則不輸出。如:有兩張表為studentexam表和student表,需要查詢返回任何一次考試中分數低於40分的學生的studentid和姓名: 

select  studentid ,name from student s 

whereexists

(select studentid from studentexam e where mark <40 and e.studentid=s.studentid)

但是,通常情況下採用exists要比in效率高。

而 all、 any (或some)需要配合關係運算子來使用,他們的左邊要聯接列名,右邊是子查詢。all對所有資料都滿足條件,整個條件才成立 ;.any只要有任一條資料滿足條件,整個條件就成立;some和any一樣表示的限制相同。

一般情況下:

(1)=any 運算子與 in 等效。如:在bbc表中,要查詢出和india(印度)、iran(伊朗)所在地區的所有國家的所有資訊:

select * from bbc

where region= any

(select region from bbc where name='india'or name='iran')

select *  from bbc

where regionin

(select region from bbc where name='india'or name='iran')

(2)>any運算子與》min等效。

(3)

select studentid,grade from enrollment e

where grade

< any

(select mark/2 from studentexam s where s.studentid=e.studentid

)

select studentid,grade from enrollment e

where grade< (select

max

(mark/2 )from studentexam s where s.studentid=e.studentid

)

(4)>all運算子和》max等效。如bbc表中,要查詢出gdp比任何歐洲國家都多的國家:

select name from bbc

where gdp>(selectmax

(gdp) from bbc where region='europe') 

select name from bbc

where gdp

>all

(select gdp from bbc where region='europe')  

(5)

SQL中的運算子

select from student where sid 1001 select from student where sid 1001 sql中運算子 sql select from student where score 60 select from student where score 6...

運算子之間的區別

運算法則 運算子運算法則 a ba與b相加 a ba與b相減 a ba與b相乘 a.b a與b相應元素相乘 a b為同緯度的矩陣 a ba與b相除 a b為數值或矩陣 a.b a與b相應元素相除 a b為同緯度的矩陣 a ba的b次冪 a b為數值或矩陣 a.b a的每個元素的b次冪 a b為同緯度...

sql中的三元運算子

作用 將輸入數值與函式中的引數列表相比較,根據輸入值返回乙個對應值。函式的引數列表是由若干數值及其對應結果值組成的若干序偶形式。當然,假如未能與任何乙個實參序偶匹配成功,則函式也有預設的返回值。區別於sql的其它函式,decode函式還能識別和操作空值。語法 decode control value...