I've got the following query:
select distinct a.id, a.name
from Employee a
join Dependencies b on a.id = b.eid
where not exists
(
select *
from Dependencies d
where b.id = d.id
and d.name = 'Apple'
)
and exists
(
select *
from Dependencies c
where b.id = c.id
and c.name = 'Orange'
);
I have two tables, relatively simple. The first Employee has an id column and a name column The second table Dependencies has 3 column, an id, an eid (employee id to link) and names (apple, orange etc).
the data looks like this Employee table looks like this
id | name
-----------
1 | Pat
2 | Tom
3 | Rob
4 | Sam
Dependencies
id | eid | Name
--------------------
1 | 1 | Orange
2 | 1 | Apple
3 | 2 | Strawberry
4 | 2 | Apple
5 | 3 | Orange
6 | 3 | Banana
As you can see Pat has both Orange and Apple and he needs to be excluded and it has to be via joins and i can't seem to get it to work. Ultimately the data should only return Rob
You can usually use IN sub-queries to get the same results as EXISTS sub-queries: For example: SELECT c, d, e, f FROM a WHERE (c, d, e) NOT IN ( SELECT c, d, e FROM b ) ; An anti-join is another way, but it would probably be less efficient than either NOT IN or NOT EXISTS.
The WHERE NOT EXISTS() subquery will only return rows where the relationship is not met. However, if you did a LEFT OUTER JOIN and looked for IS NULL on the foreign key column in the WHERE clause, you can make equivalent behavior to the WHERE NOT EXISTS .
Using Joins Instead of IN or EXISTS An alternative for IN and EXISTS is an INNER JOIN, while a LEFT OUTER JOIN with a WHERE clause checking for NULL values can be used as an alternative for NOT IN and NOT EXISTS.
Inner join with the name you want, left join on the name you dont, then use where to ensure the left join fails to match, like so (SQL Fiddle):
select distinct a.id, a.name
from Employee a
inner join Dependencies b on a.id = b.eid
and b.name = 'Orange'
left join Dependencies c on ( a.id = c.eid
and c.name = 'Apple')
where c.id is null;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With