【DB2】NOT IN使用中的大坑


1.環境准備

------建表TB
DROP TABLE TB;

CREATE TABLE TB
    (
    ID           INTEGER,
    LEVEL_DETAIL VARCHAR (100)
    );
INSERT INTO TB (ID, LEVEL_DETAIL)
VALUES (1, 'A');

INSERT INTO TB (ID, LEVEL_DETAIL)
VALUES (NULL, 'A');

INSERT INTO TB (ID, LEVEL_DETAIL)
VALUES (2, 'B');

INSERT INTO TB (ID, LEVEL_DETAIL)
VALUES (1, 'A++');

INSERT INTO TB (ID, LEVEL_DETAIL)
VALUES (1, 'A--');
----建表TB_TEMP
DROP TABLE TB_TEMP;

CREATE TABLE TB_TEMP
    (
    ID           INTEGER,
    LEVEL_DETAIL VARCHAR (100)
    );

INSERT INTO TB_TEMP (ID, LEVEL_DETAIL)
VALUES (1, 'A');

INSERT INTO TB_TEMP (ID, LEVEL_DETAIL)
VALUES (2, 'B');

INSERT INTO TB_TEMP (ID, LEVEL_DETAIL)
VALUES (1, 'A++');

INSERT INTO TB_TEMP (ID, LEVEL_DETAIL)
VALUES (1, 'A--');

INSERT INTO TB_TEMP (ID, LEVEL_DETAIL)
VALUES (3, 'CCC');

INSERT INTO TB_TEMP (ID, LEVEL_DETAIL)
VALUES (4, 'CCC');

INSERT INTO TB_TEMP (ID, LEVEL_DETAIL)
VALUES (4, 'C');

INSERT INTO TB_TEMP (ID, LEVEL_DETAIL)
VALUES (5, 'AA');

數據展示:

TB表

image

TB_TEMP表

image

---使用IN
SELECT * FROM TB_TEMP WHERE ID IN (SELECT ID FROM TB GROUP BY ID)

image

 

--EXISTS
SELECT * FROM TB_TEMP A WHERE EXISTS (SELECT 1 FROM TB B WHERE A.ID=B.ID)

image

 

--NOT IN (跟預期結果不一致)
SELECT * FROM TB_TEMP WHERE ID NOT IN (SELECT ID FROM TB GROUP BY ID)

預期結果:

ID LEVEL_DETAIL
3 CCC
4 CCC
4 C
5 AA

實際結果:

image

--NOT EXISTS(沒問題)
SELECT * FROM TB_TEMP A WHERE NOT EXISTS (SELECT 1 FROM TB B WHERE A.ID=B.ID)
image

在使用過程中,盡量不要使用NOT IN ,當列中出現了NULL值,那么將會無結果返回(NULL不是具體的值,做二元運算符時,計算結果也為NULL)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM