问题
Trying to fix someone else's code. The NOT IN kills performance. I took it out and replaced with Not Exists and I'm getting different results. The commented out not in is just above my not exists. Anyone see anything stupid I'm doing here?
IF @ProcessComplete = 1
BEGIN
-- PRINT 'Group-Complete'
INSERT INTO @ProcessIDTable
SELECT DISTINCT(ProcessID)
FROM vPortalInbox
WHERE GroupUserIDs LIKE '%,' + CAST(@UserID AS VARCHAR(MAX)) + ',%'
AND StepOwnerID IS NULL
--AND ProcessID NOT IN (SELECT ProcessID FROM @ProcessIDTable)
And not exists (SELECT ProcessID FROM @ProcessIDTable)
回答1:
You could try:
And not exists (
SELECT ProcessID
FROM @ProcessIDTable
WHERE ProcessID = vPortalInbox.ProcessID)
...or possibly even better still: you could try a (left or right) outer join to vPortalInbox
on ProcessID
, and specify in your WHERE
clause that @ProcessIDTable.ProcessID IS NULL
:
...
SELECT DISTINCT(ProcessID)
FROM vPortalInbox LEFT OUTER JOIN @ProcessIDTable
ON vPortalInbox.ProcessID = @ProcessIDTable.ProcessID
WHERE GroupUserIDs LIKE '%,' + CAST(@UserID AS VARCHAR(MAX)) + ',%'
AND StepOwnerID IS NULL AND @ProcessIDTable.ProcessID IS NULL
回答2:
1 --AND ProcessID NOT IN (SELECT ProcessID FROM @ProcessIDTable)
2 And not exists (SELECT ProcessID FROM @ProcessIDTable)
The above two statements are not same. The not exist will evaluate to true only when you get no rows from the subquery inside the brackets following the not exists clause. Since you have no conditions for the sub-query following not exists clause, it will never return 0 rows unless the table is empty.
Try using this where clause:
FROM vPortalInbox P1
WHERE GroupUserIDs LIKE '%,' + CAST(@UserID AS VARCHAR(MAX)) + ',%'
AND StepOwnerID IS NULL
And not exists (SELECT 1 FROM @ProcessIDTable P2
where P1.ProcessID = P2.ProcessID )
来源:https://stackoverflow.com/questions/19824241/sql-replaced-not-in-with-not-exists-and-results-differ