SQL自連線查詢使用EXISTS替代

2021-10-08 17:09:22 字數 1600 閱讀 5676

select

* from

cmooc_course a

where

a.valid = 'y' and a.id in (

select distinct a.course_id from cmooc_course_belong_scope a inner join cmooc_course_belong_scope b on a.course_id = b.course_id

and a.belong_type = '5' and b.belong_type = '6' and a.belong_code = '86480024' and b.belong_code = 'a' and a.valid = 'y' and b.valid = 'y')

select

* from

cmooc_course a

where

a.valid = 'y'

and exists ( select 1 from cmooc_course_belong_scope c where a.id = c.course_id and c.belong_type = '5' and c.belong_code = '86480024' )

and exists ( select 1 from cmooc_course_belong_scope c where a.id = c.course_id and c.belong_type = '6' and c.belong_code ='a' )

select

* from

cmooc_course a

where

a.valid = 'y'

and a.id in (select c.course_id from cmooc_course_belong_scope c where c.belong_type = '5' and c.belong_code = '86480024' and c.valid = 'y')

and a.id in (select c.course_id from cmooc_course_belong_scope c where c.belong_type = '6' and c.belong_code ='a' and c.valid = 'y')

in 和 exists的區別: 如果子查詢得出的結果集記錄較少,主查詢中的表較大且又有索引時應該用in, 反之如果外層的主查詢記錄較少,子查詢中的表大,又有索引時使用exists。其實我們區分in和exists主要是造成了驅動順序的改變(這是效能變化的關鍵),如果是exists,那麼以外層表為驅動表,先被訪問,如果是in,那麼先執行子查詢,所以我們會以驅動表的快速返回為目標,那麼就會考慮到索引及結果集的關係了 ,另外in時不對null進行處理。

in 是把外表和內錶作hash 連線,而exists是對外表作loop迴圈,每次loop迴圈再對內表進行查詢。一直以來認為exists比in效率高的說法是不準確的。

如果查詢語句使用了not in 那麼內外表都進行全表掃瞄,沒有用到索引;而not extsts 的子查詢依然能用到表上的索引。所以無論那個表大,用not exists都比not in要快。

SQL自連線查詢

問題 表testcolor title color sign a 紅 111 b 紅 222 a 綠 333 c 紅 444 轉檢視 title 紅 綠 a 111 333 b 222 null c 444 null 解答 declare sql nvarchar 1000 set sql sele...

SQL查詢 內連線 外連線 自連線查詢

先建立2個表 學生表和教師表 在每個表中找出符合條件的共有記錄。x inner join y on.第一種寫法 只用where select t.teacher name,s.student name from teacher t,student s where t.id s.teacher id ...

mysql自連線查詢 Mysql自連線查詢例項詳解

自連線查詢 假想以下場景 某一電商 想要對站內產品做層級分類,乙個類別下面有若干子類,子類下面也會有別的子類。例如數碼產品這個類別下面有筆記本,台式電腦,智慧型手機等 筆記本,台式電腦,智慧型手機又可以按照品牌分類 品牌又可以按照 分類,等等。也許這些分類會達到乙個很深的層次,呈現一種樹狀的結構。那...