从表1中获取记录,并在表2值不存在时从另一个表中加入

时间:2017-12-27 14:42:39

标签: mysql sql

第一张表 - explore_offers:

- id
- Primary Key - offer_unique

第二张表 - visited_explore_offers:

- id
- email - user_email
- Primary Key - offer_unique

我想要的: *显示第一个表记录,并排除那些在第二个表中找到特定电子邮件的记录

前:

SELECT eo.*
     , peo.user_email 
  FROM explore_offers eo 
  LEFT 
  JOIN participated_explore_offers peo 
    ON eo.offer_unique = peo.offer_unique
 WHERE peo.user_email = 'test@gmail.com'

我已经尝试了这个例子,我获得了0条记录。 我在第一个表中有2条记录,在第二个表中有一条记录,我想要的结果是:

*。从第一个表中获取一条记录,第二个表中不存在该记录。

第1表内容:

Nr id  Primary Key
1  0   m1
2  1   m2

第二桌内容

Nr id user_email      Primary Key
1  0  test@gmail.com  m1
1  0  test2@gmail.com  m2

预期

Nr id Primary Key
1  1  m2

我有什么:

0记录

2 个答案:

答案 0 :(得分:2)

SQL DEMO

试试这个:

select * from explore_offers
where offer_unique not in 
(select offer_unique from participated_explore_offers where user_email='test@gmail.com')

答案 1 :(得分:1)

将电子邮件过滤移至JOIN条件,使其与LEFT JOIN一起使用:

SELECT eo.*,peo.user_email 
FROM explore_offers eo 
LEFT JOIN participated_explore_offers peo ON (eo.offer_unique = peo.offer_unique) 
                                          AND peo.user_email = 'test@gmail.com'
WHERE peo.user_email is null;

demo

| Nr | id | offer_unique | user_email |
|----|----|--------------|------------|
|  2 |  1 |           m2 |     (null) |
相关问题