I have a table of Companies
that I’d like to filter to just the records that are referenced from two other tables, Employees
and Contracts
.
My initial instinct is that I might be able to do something like this:
SELECT c.* FROM Companies c JOIN Employees ON EmployerId = c.Id JOIN Contracts ON CompanyId = c.Id
However, this selects the records that are referenced from both Employees
and Contracts
tables.
How do I rewrite this query to match records that are referenced from either table?
Advertisement
Answer
I initially put up a buggy version that failed, with LEFT OUTER JOINS. It could have been fixed but it’s actually probably more efficient to use WHERE EXISTS e.g.,
SELECT c.* FROM Companies c WHERE EXISTS (SELECT EmployerID FROM Employee WHERE EmployerID = c.ID) OR EXISTS (SELECT CompanyId FROM Contracts WHERE CompanyId = c.ID)
The reason my previous version was buggy, was that it had a join to Employees and Contracts, which meant it would return one row for every one that existed (and indeed, possibly the cross-product of results). Even with a GROUP BY or DISTINCT, it is likely SQL Server would have had to do a lot of work.
The above solution just gets one row per Company, regardless of number of employees or contracts.