选择不在一组中的不同记录

时间:2018-05-23 14:46:52

标签: sql postgresql

我有一个客户表,其中包含客户联系方式。

客户可以通过以下三种方式之一联系:

  • 电话(1)
  • 短信(2)
  • 电子邮件(3)

FK id在括号中。

如果我想为短信和电子邮件提取不同客户ID的列表,我可以执行以下操作:

SELECT DISTINCT customer_id 
FROM contact_options 
WHERE contact_option_type_id IN (2,3)

但我该怎么办呢?假设我想要一个没有电话联系的客户列表(DISTINCT)。我可以不使用子查询吗?

我意识到这个例子是人为的,在实践中我有很多不同的联系方式(大约80个)。

2 个答案:

答案 0 :(得分:1)

一种选择是使用聚合:

SELECT customer_id
FROM contact_options
GROUP BY customer_id
HAVING SUM(CASE WHEN contact_option_type_id = 1 THEN 1 ELSE 0 END) = 0;

我们也可以尝试使用EXISTS

SELECT DISTINCT customer_id
FROM contact_options c1
WHERE NOT EXISTS (SELECT 1 FROM contact_options c2
    WHERE c1.customer_id = c2.customer_id AND c2.contact_option_type_id = 1);

答案 1 :(得分:0)

您可以使用not exists

select distinct c.customer_id
from contact_options c
where not exists (select 1 
                   from contact_options
                   where customer_id = c.customer_id and 
                         contact_option_type_id  = 1
                  );

如果你有正确的索引,我认为exists没有性能问题。

相关问题