使用NOT IN提取数据

时间:2012-09-26 13:55:24

标签: sql

我是sql的新手,遇到了一个小问题。 我的查询是这样的:

select cust_id, count(1) from all_customers
group by cust_id
having count(1)>4;

该查询为我提供了我想要的结果。

我需要对all_customers表中的所有客户进行新查询,并从上面的查询中排除我刚刚得到的结果。 我尝试过这样的事情:

select * from all_customers
where cust_id NOT IN 
(
    select cust_id, count(1) from all_customers
    group by cust_id
    having count(1)>4
)

但是我收到错误消息too many values。 我做错了什么?

2 个答案:

答案 0 :(得分:6)

您应该删除NOT IN子句中的聚合列。原因是您只是比较cust_id列。另请注意,使用NOT IN时,子查询应始终返回单列。

select * 
from all_customers
where cust_id NOT IN 
      (
         select cust_id 
         from all_customers
         group by cust_id
         having count(1)>4
      )

答案 1 :(得分:1)

子查询中有很多列,请尝试:

select * from all_customers
where cust_id NOT IN 
(select cust_id
 from all_customers
 group by cust_id
 having count(1)>4)