2013-08-24 33 views
0

我使用WHERE XXX IN(SQL),所以(SQL)只能选择一列SQL HAVING未知列

在这种情况下,我从一组选择一些customer_id,这些客户只属于该组只有

WHERE `id_customer` IN(
SELECT g.`id_customer` // this must select *only one* column 
FROM ps_customer_group AS g 
Group By g.`id_customer` 
Having COUNT(g.`id_customer`) = 1 
AND g.`id_group`=3 // **- Unknown column 'g.id_group' in 'having clause'** 
) 

的原始数据是这样的,顺便说一句,这是没有结果
enter image description here

+0

首先,您正在通过'id_customer'进行分组并搜索count = 1。因此它会返回多个值。 – hims056

+0

nono,这是原始数据不是结果,sql我只运行显示语法错误 –

+0

我完全不明白,你想知道用户是否只属于一个组? –

回答

2

试试这个:

WHERE id_customer IN(

    select g.id_customer from 
    ps_customer_group as g 
    where g.id_group=3 -- That belongs to this group 
    and g.id_customer in(

     SELECT g.id_customer 
     FROM ps_customer_group AS g 
     Group By g.id_customer 
     Having COUNT(g.id_group) = 1 -- is his only group 
    ) 

) 

这里是一个test

2

如果你想知道,如果客户属于一个组(ID = 3)只,你必须改变你的查询:

select g.id_customer 
    from ps_customer_group AS g 
where g.id_customer in (
     select id_customer 
      from ps_customer_group 
      where id_group=3 
     ) 
Group By g.id_customer 
Having COUNT(distinct g.id_group) = 1 

这将列出所有属于#3组的客户并没有其他组。