I have a table Foo
FOO
-------
id
name
BAR
-------
id
name
FOO_BAR_XREF
-------
foo_id
bar_id
I need to select all instances of FOO where foo.id has a record in foo_bar_xref with a bar_id of 1 and exclude records from foo where foo.id has a record n foo_bar_xref with a bar_id of 2
foo -> foo_bar_xref is one to many *emphasized text*foo_bar_xref may contain multiple bar_id’s per foo_id
Is this possible with only joins or do I need to use not exists statements in the where clause?
so far I have
select f.name from FOO f
inner join FOO_BAR_XREF fb_1 on fb_1.foo_id = f.id
inner join FOO_BAR_XREF fb_2 on fb_2.foo_id = f.id
where fb_1.bar_id = 1 and fb_2.bar_id <> 2
group by f.name -- remove dupes - running on sql server and is paged with sql servers hackish over keyword where distinct doesn't work so well.
thats not filtering out the foo’s that have a bar of 2
THIS seems to work but I’m not sure it’s the most efficient
select f.name from FOO f
inner join FOO_BAR_XREF fb_1 on fb_1.foo_id = f.id and fb_1.bar_id = 1
left outer join FOO_BAR_XREF fb_2 on fb_2.foo_id = f.id and fb_2.bar_id = 2
where fb_2.bar_id is null
group by f.name -- remove dupes
To reiterate my comment, I think OP has best solution. I have always preffered using left joins for these scenarios.
And the SQL Fiddle.
BTW, I think this is the most efficient solution in regards to table scans. Check your execution plans and see what you have going on.