2010-11-29 13 views
0
 
I have a simple structure of 2 tables: contacts and group_contacts. 

A contact can belong to one, many or no groups. 

I'm trying to write a select statement that will give me all the contacts 
that don't belong to group_id '123'. The negative, don't, has me confused. 

CREATE TABLE IF NOT EXISTS `contacts` (
    `contact_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, 
    `name` varchar(50) NOT NULL) 

CREATE TABLE IF NOT EXISTS `group_contacts` (
    `contact_id` bigint(20) unsigned NOT NULL, 
    `group_id` int(11) unsigned NOT NULL) 



thanks 

回答

3

您将有两个宏步进行的:

  1. 首先,您需要在联系人和group_contacts表之间留下外部联结,以便选择所有在group_contacts表中具有且没有任何相关联系的联系人
  2. 然后在group_contacts的where子句中应该加载123的group_id。
1

试试这个

select * from contacts a left join group_contacts b 
on a.contact_id = b.contact_id 
where b.group_id !=123 
+0

查询语法错误。请检查。我不确定我们可以使用像“左连接B group_contacts”.Alias名称应该在表名之后 – 2010-11-29 06:33:46

+0

我修正了谢谢,它错字错误B需要在表名后加上 – 2010-11-29 06:35:51

2
select * from contacts as ct 
left join group_contacts as gc on ct.contact_id=gc.contact_id 
where gc.group_id!=123 
3
select a.contact_id from contacts a, group_contacts b where b.group_id<>123 and b.contact_id=a.contact_id; 
相关问题