sql之獨立子查詢和相關子查詢總結

2022-05-24 04:36:09 字數 2675 閱讀 1523

1、獨立子查詢:顧名思義:就是子查詢和外層查詢不存在任何聯絡,是獨立於外層查詢的:

下面就看乙個例子:

有一張訂單表 sales.order 和一張 客戶表 sales.customer

下面的sql 語句是為了查詢出sales.customer裡 custid(使用者id)不在 sales.order 的custid

1

select

custid

2from

[sales.customers]3

where custid notin4

(5select

custid

6from

[sales.orders

]7 )

下面我再來舉乙個例子:

業務要求:查詢出每個客戶的訂單的數量:

1

select

distinct

custid,2(

3select

count(*)4

from

[sales.orders]5

--6where

[sales.orders

].custid=

[sales.customers

].custid

7 ) as

ordernum

8from

[sales.customers

]

查詢的結果:

所以我們不難看出:相關子查詢比獨立子查詢實現的功能強大的多

3、下面我再來介紹一下 exists 的使用(個人認為:這個有時好用但是有時也很不好用)

業務要求:這裡要用到一張表 **商表([production.supplier]),查詢出 客戶表中的 公司名稱companyname 不再[production.supplier] 裡的 資料

使用獨立子查詢實現:

1

select

distinct

companyname

2from

[sales.customers]3

where companyname notin4

(5select

distinct companyname from

[production.supplier

]6 )

select

distinct

companyname

from

[sales.customers]--

exists:是否存在

where

notexists

(

select companyname from

[production.supplier]--

這個是對於 每一次查詢出的 外層資料 在 子查詢裡面進行使用

where

[production.supplier

].companyname =

[sales.customers

].companyname

)

3、高階子查詢

1、業務要求:查詢出 order 表面的orderid 以及其 對應的 相鄰的前面的和相鄰的後面的 orderid(注意由於是訂單表,可能前後的訂單之間的大小並不是相差1):使用相關子查詢:

1

select

orderid,2(

3select

max(orderid)

4from

[sales.orders]as

innerorder

5where innerorder.orderid<

outerorder.orderid

6 ) as

primerorderid,7(

8select

min(orderid)

9from

[sales.orders]as

innerorder

10where innerorder.orderid >

outerorder.orderid

1112 ) as

lastorderid

13from

[sales.orders

]as outerorder

2、連續聚合(使用相關子查詢)

業務要求:對orderid實現 累加的結果作為乙個查詢字段進行輸出

1

select

orderid,2(

3select

sum(orderid)

4from

[sales.orders]as

innerorder

5where innerorder.orderid<=

outerorder.orderid

6 ) as

totalorderid

7from

[sales.orders

]as outerorder

查詢效果:

mysql相關子查詢 SQL子查詢與連線查詢研究

假設有a b兩張表,其中b表有a表的外來鍵。在sql查詢中,我們經常有這樣的需求,需要根據b表中的條件篩選去查詢a表中的內容,以工作流查詢使用者的已辦流程為例來說明 1 歷史流程例項表act hi procinst 下述用a表代替 create table act hi procinst id va...

什麼是 相關子查詢 和 非相關子查詢

先執行主查詢,再針對主查詢返回的每一行資料執行子查詢,如果子查詢能夠返回行,則這條記錄就保留,否則就不保留。舉例1 相關子查詢查詢 查詢所有是領導的員工資訊 select from emp e1 where exists select from emp e2 where e1.empno e2.mg...

Mysql 非相關子查詢和相關子查詢的執行解析

前段時間有乙個相關子查詢的sql語句,看不太懂他是如何執行的,為什麼會出現那個結果。著實糾結了一把。下面來講一下非相關子查詢和相關子查詢的執行過程是怎樣的。先看乙個非相關子查詢到sql語句。需求 查詢學生表student和學生成績表grade中成績為70分的學生的基本資訊。select t.sno,...