使用連線來代替in和not in(使用外連線技巧)

2022-02-04 22:51:18 字數 1236 閱讀 6000

比如:表a裡面的乙個字段叫做mobile 裡面存的記錄如下:1

2345

6781

表b裡面的乙個欄位也叫做mobile裡面存的記錄如下12

3419

10(1)我們要查詢一下a和b裡面都有的,以前我使用的是

select a.mobile from  a where a.mobile in (select b.mobile from b)

出來結果為:11

234沒關係,去除重複就得到結果1,2,3,4了

現在我們使用另外一種sql呢:

select a.mobile from a,b where a.mobile=b.mobile

結果為112

3411

同樣濾重得到結果1,2,3,4

(2)第二個實驗我們要取一下在a中有的,而在b中沒有的,以前我都是使用not in 不要太熟練了,呵呵!不過從來也不考慮個效率。

select  a.mobile from  a where a.mobile not in (select b.mobile from b)

得出結果56

78然後我們再使用連線在處理

select a.mobile from a,b where a.mobile=b.mobile(+) and b.mobile is null

這條語句還可以表示為:

select a.mobile from a left outer  join b on (a.mobile=b.mobile) where b.mobile is null

結果為:65

78(3) 第三個實現我們要取b中有的,而a中沒有的,直接用連線了

select b.mobile from b left outer join a on (b.mobile=a.mobile) where a.mobile is null

等價於select b.mobile from a,b where a.mobile(+)=b.mobile and a.mobile is null 

等價於select b.mobile from a right outer join b on (a.mobile=b.mobile) where a.mobile is null

結果為:109

這樣的話大家應該對左外連線,右外連線有個理解了吧!!!使用連線肯定是要比not in 的效率高多了,這可不是我說的dba說的!呵呵!oracle10g測試通過!

Mysql使用外連線替換in和not in

在程式中,我們經常會習慣性的使用in和not in,在訪問量比較小的時候是可以的,但是一旦資料量大了,我們就推薦使用not exists或者外連線來代替了。如果要實現一張表有而另外一張表沒有的資料時,我們通常會這麼寫 select from table twhere t.id notin selec...

SQL優化 避免使用 IN 和 NOT IN

1 效率低 2 容易出現問題,或查詢結果有誤 不能更嚴重的缺點 insert into test2 id2 values null 跑題一句 建表的時候最好不要允許含空值,否則問題多多。1 用 exists 或 not exists 代替 select from test1 where exists...

pandas is in和not in的使用說明

pandas按條件篩選資料時,除了使用query 方法,還可以使用isin和對isin取反進行條件篩選.import pandas as pd df pd.dataframe filter condition df in df df.isin filter condition a df notin ...