繁体   English   中英

从表1中获取记录,并在表2值不存在时从另一个表中连接它

[英]Get records from table 1 and join it from another table when the table 2 value does not exist

第一张表 - 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记录

SQL DEMO

尝试这个 :

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

将电子邮件过滤移动到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;

演示

| Nr | id | offer_unique | user_email |
|----|----|--------------|------------|
|  2 |  1 |           m2 |     (null) |

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM