【问题标题】:Get records from table 1 and join it from another table when the table 2 value does not exist当表2值不存在时,从表1中获取记录并从另一个表中加入
【发布时间】:2017-12-27 14:42:39
【问题描述】:

第一个表 - explore_offers:

- id
- Primary Key - offer_unique

第二张桌子 - 参与的_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 条记录,在第二个表中有一条,我想要的结果是:

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

第一个表格内容:

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 条记录

【问题讨论】:

  • 您已尝试解释,但最好提供一些示例数据和所提供数据的预期输出。
  • 添加了内容和预期。

标签: mysql sql


【解决方案1】:

SQL DEMO

试试这个:

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

【讨论】:

  • 这是正确的,但对我的问题不正确。此查询仅显示没有任何电子邮件的记录,但我会有很多不同电子邮件的记录,我希望查询特定于所选电子邮件。
  • 请查看其他问题的评论。
  • 回答你的严肃问题:我认为我提供的查询会有更好的性能。如果您有大型数据集,您可以轻松地在数据库中检查它。您也可以为此发布一个新问题:)
【解决方案2】:

将电子邮件过滤移至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) |

【讨论】:

  • 这个查询显示了有邮件的记录,我想排除它。
  • @Jaeger 所以你想要那些没有电子邮件test@gmail.com的记录??还是什么??
  • 是的,我想要第一个表中的记录,其中不包含来自第二个表的电子邮件。
  • 请检查我添加的预期内容和表格内容。
  • @Jaeger - 查看我的更新答案,如果现在修复,您可以尝试在线演示,
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-08-27
  • 1970-01-01
  • 2017-05-27
  • 2018-05-28
  • 2010-12-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多