在连接表中不存在值的位置

时间:2016-03-05 03:11:55

标签: mysql

我正在使用此查询来查找users表中是否存在来自emails_sent的电子邮件地址。

SELECT users.email,users.registration_date 
FROM users 
LEFT JOIN emails_sent
ON emails_sent.email=users.email
WHERE emails_sent.email IS NULL
ORDER BY registration_date DESC
LIMIT 0,50

相反,我想返回users.email,其中没有emails_sent.type ='welcome'的记录

我尝试过以下但是没有返回任何结果

SELECT users.email,users.registration_date 
FROM users 
LEFT JOIN emails_sent
ON emails_sent.email=users.email
WHERE emails_sent.type!='welcome'
ORDER BY registration_date DESC
LIMIT 0,50

emails_sent表格如下

id  int(11) unsigned    NO  PRI NULL
email   varchar(200)    YES     NULL
type    varchar(200)    YES     NULL
timestamp   int(200)    YES     NULL

1 个答案:

答案 0 :(得分:2)

只需在LEFT-JOIN部分包含“AND”条件,而不是WHERE

SELECT 
      users.email,
      users.registration_date 
   FROM 
      users 
         LEFT JOIN emails_sent
            ON users.email = emails_sent.email
           AND emails_sent.type = 'welcome'
   where
       emails_sent.email IS NULL
   ORDER BY 
      registration_date DESC
   LIMIT 
      0,50

因此,您的加入符合匹配用户和特定“欢迎”电子邮件的两个标准。 Ø