peters
peters

Reputation: 79

Excluding values SQL

SELECT m.name, f.name
FROM   delivered d
JOIN   members m ON d.member_id = m.id
JOIN   members f ON d.friend_member_id = f.id
WHERE  m.shipping_method = f.shipping_method AND
       m.zip_code = f.zip_code

I need help joining this to a third table called method. The friend_member_id above will join to the member_id in this table. Problem is there could be multiple records for the friend_member_id in the method table and I need to exclude any friend_member_id that has at least one record where type = 'express'. Basically if it is the case a friend_member_id has any record in the method table with type = 'express' I do not want to return that name.

Upvotes: 0

Views: 41

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1269443

Instead of a JOIN, use a NOT EXISTS:

SELECT m.name, f.name
FROM delivered d JOIN
     members m
     ON d.member_id = m.id JOIN
     members f
     ON d.friend_member_id = f.id
WHERE  m.shipping_method = f.shipping_method AND
       m.zip_code = f.zip_code AND
       NOT EXISTS (SELECT 1
                   FROM method mm
                   WHERE mm.member_id = d.friend_member_id AND
                         mm.type = 'express'
                  );

Upvotes: 1

Related Questions