2017年8月29日 星期二

【TSQL】NOT EXIST doesn't return expected result

把 NOT IN 改成 NOT EXIST 結果什麼都查不到

昨天真的是突然腦袋燒到
SELECT M.CustomerID
FROM [TableA] M
WHERE M.LoanCaseID=@loanCaseId
  AND M.CustomerID NOT IN
    (SELECT DISTINCT CustomerID
     FROM [TableB]
     WHERE LoanCaseID=@loanCaseId)
ORDER BY M.CustomerID

改成
SELECT M.CustomerID
FROM [TableA] M
WHERE M.LoanCaseID=@loanCaseId
  AND NOT EXISTS
    (SELECT DISTINCT 1
     FROM [TableB]
     WHERE LoanCaseID=@loanCaseId)
ORDER BY M.CustomerID

發現怎麼突然什麼都沒查到? ...

SELECT M.CustomerID
FROM [TableA] M
WHERE M.LoanCaseID=@loanCaseId
  AND NOT EXISTS
    (SELECT DISTINCT 1
     FROM [TableB]
     WHERE LoanCaseID=@loanCaseId AND 
     CustomerID = M.CustomerID)
ORDER BY M.CustomerID
相對於原本 M.CustomerID NOT IN (SELECT DISTINCT CustomerID) 的
WHERE LoanCaseID=@loanCaseId AND CustomerID = M.CustomerID 沒寫,當然什麼都不會查到...

沒有留言:

張貼留言