in 跟not in一體兩面的範例

in與not in的效能問題篇中,有網友提到不太了解「對於{in 跟not in一體兩面,能下in就能下not in}不太了解,我簡單寫了個範例,以下使用Northwind資料庫中Customers資料表為例,用簡單範例來完整表現整個in與not in的精華:

use Northwind 
go

/* 使用in,找出城市為London的資料 */
select CustomerID, City
from customers
where CustomerID in (
 select CustomerID
 from Customers
 where City = 'London')
/* 上面的in子查詢,帶入6個where條件 */

/* 使用not in,找出城市為London的資料 */
/* 因為使用not in,所以要帶入「相反」條件,給not in非London的資料 */
select CustomerID, City
from customers
where CustomerID not in (
 select CustomerID
 from Customers
 where City <> 'London') 
/*上面的not in子查詢,帶入85個where條件 */
go

上面的差異很清礎了吧,6比85,好壞立刻分曉!在只有91筆的資料裡就可以差數十倍,那資料不用到幾十萬、幾百萬筆,那更是差數百到數千倍。

好的SQL語法讓你住樓房,
壞的SQL語法讓你住套房。
^_^

以下為同樣結果:

CustomerID City
---------- ---------------
AROUT      London
BSBEV      London
CONSH      London
EASTC      London
NORTS      London
SEVES      London

(6 個資料列受到影響)

CustomerID City
---------- ---------------
AROUT      London
BSBEV      London
CONSH      London
EASTC      London
NORTS      London
SEVES      London

(6 個資料列受到影響)

2 則留言:

  1. 您好:

    我是昨天的發問者,
    您舉的例子很清楚,
    一目了然,
    感謝!

    P.S.文章讓我想到某位老師。

    Q:為何我查詢的效能這麼慢....
    A:老師說過的你有沒有在聽? 沒有嘛!(摔筆)

    回覆刪除
  2. 謝謝分享
    您的文章很有參考價值

    回覆刪除

感謝您的留言,如果我的文章你喜歡或對你有幫助,按個「讚」或「分享」它,我會很高興的。