SQL where子句在同一列上有两个条件

时间:2017-11-03 13:24:47

标签: sql

这里的第一个问题。 我有一个SQL查询,需要验证用户是否收到了“打开”电子邮件,但没有收到“确认”邮件。为此我加入了两个表(一个包含用户数据,另一个包含邮件数据)。

select u.username, m.username, m.subjectDescription 
from users u 
inner join mails m on m.username = u.username + '@hotmail.com' 
where m.SubjectDescription like '%open%' 
and (m.subjectDescription not like '%confirmation%')

此查询仅显示具有“打开”的邮件,但如果我按用户检查用户,则大多数邮件已收到确认函。我只需要检索那些收到“打开”邮件而不是“确认”邮件的用户。

4 个答案:

答案 0 :(得分:0)

一种方法是按用户对数据进行分组,并使用having子句在组级别上进行过滤

select u.username
from users u 
inner join mails m on (u.username + '@hotmail.com') = m.username  
group by u.username
having sum(case when m.SubjectDescription like '%open%' then 1 else 0 end) > 0
   and sum(case when m.SubjectDescription like '%confirmation%' then 1 else 0 end) = 0

答案 1 :(得分:0)

一种选择是LEFT OUTER JOIN到mail两次:

select u.usernum, open.usernum, open.subjectDescription 
from users u 
   LEFT OUTER JOIN mails open on 
        u.usernum = open.usernum AND
        open.subjectDescription like '%open%'
   LEFT OUTER JOIN mails conf ON
        u.username = conf.usernum AND
        conf.subjectDescription like '%confirmation%'
where open.usernum IS NOT NULL AND conf.usernum IS NULL

可选(有很多方法可以执行此操作)您可以在WHERE中使用IN子句:

select u.usernum, open.usernum, open.subjectDescription 
from users u 
   INNER JOIN mails open on 
        u.usernum = open.usernum AND
        open.subjectDescription like '%open%'       
where u.usernum IN (SELECT usernum FROM mails WHERE conf.subjectDescription like '%confirmation%')

或者,使用带有相关子查询的EXISTS:

select u.usernum, open.usernum, open.subjectDescription 
from users u 
   INNER JOIN mails open on 
        u.usernum = open.usernum AND
        open.subjectDescription like '%open%'       
where EXISTS (SELECT usernum FROM mails WHERE conf.subjectDescription like '%confirmation%' AND u.usernum = usernum)

答案 2 :(得分:0)

您可以使用EXISTSNOT EXISTS

SELECT *
FROM users u
WHERE EXISTS(SELECT 1 FROM mails
             WHERE usernum = u.usernum
             AND SubjectDescription LIKE '%open%')
AND NOT EXISTS(SELECT 1 FROM mails
               WHERE usernum = u.usernum
               AND SubjectDescription LIKE '%confirmation%');

答案 3 :(得分:0)

以下查询应该有效,并且它的逻辑非常直观。

查询说明

由于用户可以在邮件表中有两条记录,如果他或她收到了打开和确认信,那么我们只查找那些有公开信但没有确认信的用户。我们使用NOT EXISTS确保用户没有收到确认信。

SELECT u.username, 
       m.username, 
       m.subjectdescription 
FROM   users u 
       INNER JOIN mails m 
               ON m.username = u.username + '@hotmail.com' 
WHERE  m.subjectdescription LIKE '%open%' 
       AND NOT EXISTS (SELECT 1 
                       FROM   mails m1 
                       WHERE  m1.username = m.username
                              AND m1.subjectdescription LIKE '%confirmation%');