728x90

There are three ways to do such a query:

  • LEFT JOIN / IS NULL:

    SELECT  *
    FROM    common
    LEFT JOIN
            table1 t1
    ON      t1.common_id = common.common_id
    WHERE   t1.common_id IS NULL
  • NOT EXISTS:

    SELECT  *
    FROM    common
    WHERE   NOT EXISTS
            (
            SELECT  NULL
            FROM    table1 t1
            WHERE   t1.common_id = common.common_id
            )
  • NOT IN:

    SELECT  *
    FROM    common
    WHERE   common_id NOT IN
            (
            SELECT  common_id
            FROM    table1 t1
            )

When table1.common_id is not nullable, all these queries are semantically the same.

When it is nullable, NOT IN is different, since IN (and, therefore, NOT IN) return NULL when a value does not match anything in a list containing a NULL.

This may be confusing but may become more obvious if we recall the alternate syntax for this:

common_id = ANY
(
SELECT  common_id
FROM    table1 t1
)

The result of this condition is a boolean product of all comparisons within the list. Of course, a single NULL value yields the NULL result which renders the whole result NULL too.

We never cannot say definitely that common_id is not equal to anything from this list, since at least one of the values is NULL.

출처 : http://stackoverflow.com/questions/1406215/sql-select-where-not-in-subquery-returns-no-results

728x90

'DB' 카테고리의 다른 글

mysql latin1 에서 euckr 변환  (0) 2014.08.06
mssql, mysql, oracle null 값 변경하기  (0) 2014.07.06
IDENTITY_INSERT가 OFF오류  (0) 2014.06.28
mssql 금액 표시  (0) 2014.06.28
mssql 소수점 자리까지 표시  (0) 2014.06.28

+ Recent posts