2016-04-05 70 views
0

出现选择值我有3个表:不映射表

================ 
| contacts  | 
================ 
| id | name | 
================ 

================ 
| contact_map | 
================ 
| cid | lid | 
================ 

================ 
| contact_list | 
================ 
| id | name | 
================ 

我需要找到一个未分配到一个列表中的所有联系人。 cid in contact_map is id in contacts and lid in contact_map is id in contact_list

选择与lid联系是相对容易的,但我不知道如何选择那些没有lid的。

任何帮助?

回答

1

您可以使用not existsnot in

select c.* 
from contacts c 
where not exists (select 1 
        from contact_map cm 
        where cm.cid = c.id 
       ); 

如果你想不分配给特定列表中的联系人,然后就包含在子查询的信息:

select c.* 
from contacts c 
where not exists (select 1 
        from contact_map cm 
        where cm.cid = c.id and cm.lid = $lid 
       ); 
+0

你称这种类型的查询是什么?带有子查询的查询?它有一个特定的名字吗?并感谢您的答案,现在将进行测试 – Albert

+0

这些是“where”子句中相关子查询的示例。 –

1

我不您认为您实际上需要使用contact_list表,因为contact_map表允许您确定哪些联系人已添加到列表中。作为戈登答案的替代方案,您可以将LEFT JOINcontacts表格更改为contact_map,并保留任何记录,其中不是映射到的任何内容。

SELECT c.* 
FROM contacts c LEFT JOIN contact_map cm 
    ON c.id = cm.cid 
WHERE cm.cid IS NULL 
+0

感谢您的回答。我也会看看。 :) – Albert