开发者

MYSQL query to return rows that are NOT in a set

开发者 https://www.devze.com 2022-12-25 08:30 出处:网络
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.

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.


Just say WHERE Link.source_id != 8;


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


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

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


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


Shouldnt this work?

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

精彩评论

暂无评论...
验证码 换一张
取 消