Prevent Oracle minus statement from removing duplicates

前端 未结 7 1765
南方客
南方客 2021-02-15 19:39

Given these two tables:

CREATE TABLE TEST1 (TEST  VARCHAR2(1 BYTE))
CREATE TABLE TEST2 (TEST  VARCHAR2(1 BYTE))

Where TEST1 has two rows both w

7条回答
  •  温柔的废话
    2021-02-15 19:45

    The "NOT IN" answers are all correct. An alternative, which might be easier for some scenarios, is the "NOT EXISTS" operator:

    SELECT TEST FROM TEST1
    WHERE NOT EXISTS
    (SELECT null FROM TEST2 WHERE TEST2.TEST = TEST1.TEST);
    

    (Note: the "null" in the select clause is meaningless here)

    I personally use both methods, but I like the NOT EXISTS often because it is more flexible - it doesn't require the comparison to be on an equality condition, for example.

    Recent versions of the optimiser will often convert a NOT IN to a NOT EXISTS, or vice versa; however, if you're on an older version (e.g. 8i or even 9i I think) you may see performance benefits from switching between these two methods.

提交回复
热议问题