Im joining two tables and I want to then join a third but I want to get the result of the records that dont join. Dont really know what to use to do this. Can I search for nulls that appear outside the join or something?
The best-performing way to do this in general is to use NOT IN
or NOT EXISTS
- they are identical behind the scenes in SQL Server 2005+.
They are preferred over LEFT JOIN...IS NULL
because they short circuit - as soon as the matching condition is found, that record is skipped. LEFT JOIN
loads the whole data set and relation, then eliminates records afterwards.
SELECT a.*
FROM TableA a
<other joins>
WHERE a.ComparisonField NOT IN (SELECT RelationField FROM OtherTable)
or
SELECT a.*
FROM TableA a
<other joins>
WHERE NOT EXISTS(SELECT 1
FROM OtherTable o
WHERE o.Relationfield = a.Comparisonfield)
精彩评论