tags:

views:

33

answers:

5

Hi,

I have two tables:

Contact (id,name) Link (id, contact_id, source_id)

I have the following query which works that returns the contacts with the source_id of 8 in the Link table.

SELECT name FROM `Contact` LEFT JOIN Link ON Link.contact_id = Contact.id WHERE Link.source_id=8;

However I am a little stumped on how to return a list of all the contacts which are NOT associated with source_id of 8. A simple != will not work as contacts without any links are not returned.

Thanks.

+2  A: 

Just say WHERE Link.source_id != 8;

Justin Ethier
Sorry for the insults but this is a typical numb nuts reply of "lets get as much rep as I can".
igluratds
Just trying to help you out. Thanks anyway...
Justin Ethier
Sorry a bit harsh there, I guess some peoples questions are even simpler than mine!
igluratds
A: 

There's a straight-forwarrd way to do it just as you expressed it.

SELECT name FROM .... WHERE Link.source_id != 8;

le dorfier
A: 

You can change the where condition from:

Link.source_id = 8;

to

Link.source_id != 8;

You can also use <> in place of !=

Both are the not equal operator in MySQL

codaddict
+1  A: 

Use:

   SELECT c.name 
     FROM CONTACT c
LEFT JOIN LINK l ON l.contact_id = c.id
                AND l.source_id = 8
    WHERE l.contact_id IS NULL
OMG Ponies
Nice one, thank you so much. I will accept it in a few mins when I can!
igluratds
@iglurat: NP. You can also use either `NOT IN` or `NOT EXISTS`, but on MySQL the LEFT JOIN/IS NULL is more efficient: http://explainextended.com/2009/09/18/not-in-vs-not-exists-vs-left-join-is-null-mysql/
OMG Ponies
Thanks, will read into that!
igluratds
A: 

Shouldnt this work?

WHERE Link.source_id <> 8 OR Link.source_id IS NULL
mcabral