Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I replace NOT EXISTS with JOIN?

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

like image 215
YelizavetaYR Avatar asked Jun 10 '14 15:06

YelizavetaYR


People also ask

How do you replace not EXISTS with join in Oracle?

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.

How do you use not EXISTS join in SQL?

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 .

What to use instead of 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.


1 Answers

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;
like image 155
Jaaz Cole Avatar answered Oct 05 '22 22:10

Jaaz Cole