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表
TB_TEMP表
---使用IN
SELECT * FROM TB_TEMP WHERE ID IN (SELECT ID FROM TB GROUP BY ID)
--EXISTS
SELECT * FROM TB_TEMP A WHERE EXISTS (SELECT 1 FROM TB B WHERE A.ID=B.ID)
--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 |
實際結果:
--NOT EXISTS(沒問題)
SELECT * FROM TB_TEMP A WHERE NOT EXISTS (SELECT 1 FROM TB B WHERE A.ID=B.ID)
在使用過程中,盡量不要使用NOT IN ,當列中出現了NULL值,那么將會無結果返回(NULL不是具體的值,做二元運算符時,計算結果也為NULL)





