SQL select where not in select statement

筅森魡賤 提交于 2021-02-11 17:46:09

问题


I'm trying to Select all the records in my database that don't exist in a subquery.

For some reason it returns nothing even though the sub query returns 2000 or so rows on it's own and the main query returns over 5000. I need all the records that aren't contained in the subquery

SELECT ID
FROM PART
WHERE NOT ID IN 
(
SELECT DOCUMENT_ID AS ID
FROM USER_DEF_FIELDS
WHERE PROGRAM_ID = 'VMPRTMNT' AND ID = 'UDF-0000029'
)

回答1:


This is better written as a correlated NOT EXISTS subquery.

SELECT ID
  FROM PART
 WHERE NOT EXISTS 
    (
        SELECT 1
        FROM USER_DEF_FIELDS
        WHERE PROGRAM_ID = 'VMPRTMNT' 
          AND ID = 'UDF-0000029'
          AND DOCUMENT_ID = PART.ID
    )


来源:https://stackoverflow.com/questions/30923125/sql-select-where-not-in-select-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!