简体   繁体   中英

Issue with Teradata SQL query

I am having some trouble with the following SQL Query

SELECT DISTINCT A.ACC_NO
FROM FIRST_TABLE A
WHERE A.ACC_NO = 1
AND A.ACC_NO NOT IN 
(
    SELECT DISTINCT ACC_NO
    FROM SECOND_TABLE B                            
    LEFT JOIN THIRD_TABLE C
    ON B.FIELD_NAME = C.FIELD_NAME
)
ORDER BY A.ACC_NO

The follwing query doesn't return anything, even though I know for a fact that the inner select doesn't contain an entry with an ACC_NO of 1. If I run the following:

SELECT DISTINCT ACC_NO
FROM SECOND_TABLE B                            
LEFT JOIN THIRD_TABLE C
ON B.FIELD_NAME = C.FIELD_NAME
WHERE ACC_NO = 1

it doesn't return anything.

However, the query does work if I include "WHERE ACC_NO <> 1" in the inner select (of the first query).

How can this be?

NOT IN returns no rows if any value in the subquery is NULL .

For this reason, I strongly recommend that you always use NOT EXISTS rather than NOT IN . So:

SELECT DISTINCT A.ACC_NO
FROM FIRST_TABLE A
WHERE A.ACC_NO = 1 AND
      NOT EXISTS (SELECT 1
                  FROM SECOND_TABLE B LEFT JOIN                           
                       THIRD_TABLE C
                       ON B.FIELD_NAME = C.FIELD_NAME
                  WHERE ?.ACC_NO = A.ACC_NO
                 );

The ?.ACC_NO is because I don't know which table has ACC_NO , although I could speculate that it is B .

The NOT IN is rewritten to a join (check the explain). Joining with Null -values is "undefined", meaning: "no fun". Try to add "WHERE ACC_NO IS NOT NULL" to the inner SQL.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM