Henry
Henry

Reputation: 167

Exclude Record using JOIN in SQL Server

I have 3 Tables,

Table MEmployee

ID Name
1  Andy
2  Donny
3  Mark
4  John

Table Basket

ID Name
1  Andy

Table Running

ID Name
2  Donny

And I want to create Soccer table from MEmployee Exclude Basket table and Running. The result like this

Table Soccer

ID Name
3  Mark
4  John

My Query doesn't work:

SELECT * FROM MEmployee A
INNER JOIN Basket B On A.ID = B.ID
INNER JOIN Running C ON A.ID = C.ID
WHERE A.ID <> B.ID AND A.ID = C.ID

Upvotes: 2

Views: 79

Answers (2)

Yogesh Sharma
Yogesh Sharma

Reputation: 50163

You can use NOT EXISTS with CTE :

with t as (
     select id, name
     from Basket
     union all
     select id, name
     from Running
)

select e.*
from MEmployee e
where not exists (select 1 from t where t.id = e.id);

Upvotes: 1

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521168

We can try using EXCEPT here:

SELECT Name FROM MEmployee
EXCEPT
SELECT Name FROM Basket
EXCEPT
SELECT Name FROM Running;

enter image description here

Demo

Upvotes: 2

Related Questions