简体   繁体   中英

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

1st Table - explore_offers:

- id
- Primary Key - offer_unique

2nd Table - participated_explore_offers:

- id
- email - user_email
- Primary Key - offer_unique

What i want: * Show 1st Table records, and exclude those records, which are in the 2nd table with a specific email found

ex:

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'

I've tried that example, and i'm getting 0 records. I have 2 records in the first table, and one in the second table, and the result i want is:

*. get that one record from the first table, where this record does NOT exist in the second table.

1st Table content:

Nr id  Primary Key
1  0   m1
2  1   m2

2nd Table Content

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

Expected

Nr id Primary Key
1  1  m2

What i had:

0 Records

SQL DEMO

Try this :

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

Move the email filteration to the JOIN condition to make it work with 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) |

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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