0

我正在使用 WHERE XXX IN (SQL),所以 (SQL) 必须只选择一列

在这种情况下,我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'** 
)

原始数据看起来像这样,顺便说一句,这不是结果
在此处输入图像描述

4

2 回答 2

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
    )

)

这是一个测试

于 2013-08-24T05:16:52.860 回答
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 且不属于其他组的所有客户。

于 2013-08-24T05:21:41.383 回答