SQL查询以排除出现在其他行中的记录?

时间:2015-10-22 22:30:40

标签: mysql sql database

我不确定如何说出这个问题,但这是问题所在。

我有一张表subscribers的电子邮件,如下所示:

Email - Event_id
1@1.com - 123
1@1.com - 456
2@2.com - 123
3@3.com - 123
3@3.com - 123

我有一个如下所示的查询:

select email as "Email Address"

from subscribers

where event_id='123'

GROUP BY email

我希望此查询的结果为:

Email Address
2@2.com
3@3.com

但显然基于我得到的查询:

Email Address
1@1.com
2@2.com
3@3.com

基本上我想要排除与其他事件ID相关联的电子邮件,并仅收集ID为123

的ONLY事件中显示的电子邮件

3 个答案:

答案 0 :(得分:4)

只需使用having子句并将条件移到那里:

select email as "Email Address"
from subscribers
group by email
having min(event_id) = max(event_id) and min(event_id) = '123';

这表示电子邮件中的最小event_id与最大值相同(因此全部相等或NULL),值为'123'

答案 1 :(得分:3)

您可以使用IN

过滤您不感兴趣的结果
select email as "Email Address"
from subscribers
where event_id='123' 
      and email not in(
          select email as "Email Address"
          from subscribers
          where event_id<>'123')
group by email

答案 2 :(得分:1)

SELECT email as "Email Address"
FROM subscribers s
WHERE event_id ='123'
  AND NOT EXISTS (SELECT email
                  FROM subcribers s1
                  WHERE event_id <> '123'
                    AND s1.email = s.email)
GROUP BY email