【问题标题】:SQL query to exclude records that appear in other rows?SQL查询排除出现在其他行中的记录?
【发布时间】:2015-10-22 22:30:40
【问题描述】:

我不知道如何表达这个问题,但问题就在这里。

我有一个表格 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 的唯一事件中的电子邮件

【问题讨论】:

  • 为什么要使用 mysql & sqlserver 标签?您使用的是哪个 RDBMS?
  • 我想我一定是误以为他们是同一件事了?我使用的是 mysql 服务器,我认为 sql-server 是一样的

标签: mysql sql database


【解决方案1】:

只需使用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'

【讨论】:

  • 开箱即用的想法 - 不错:)
【解决方案2】:

您可以使用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

【讨论】:

  • 我现在正在尝试这个,但只是为了澄清这是一个子查询的例子吗?
【解决方案3】:
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

【讨论】:

  • @YosiDahari 对不起,我正在与存在合作,当我尝试时你没有工作,因为需要一些内部比较。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-07-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-30
  • 2013-08-15
  • 1970-01-01
相关资源
最近更新 更多