2013-08-24 65 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組的客戶並沒有其他組。