I have the following two tables
customers
| customer_id | firstname | lastname | email |
|-------------|-----------|----------|----------------------|
| 1001 | John | Doe | johndoe@gmail.com |
| 1002 | Lorem | Ipsum | loremipsum@gmail.com |
| 1003 | Alph | Beta | alphabeta@gmail.com |
And orders
| order_id | customer_id | via | status |
|----------|-------------|-----|------------|
| 100 | 1001 | WEB | pending |
| 101 | 1001 | | pending |
| 102 | 1001 | POS | pending |
| 103 | 1002 | WEB | processing |
| 104 | 1002 | APP | pending |
| 105 | 1001 | APP | completed |
| 106 | 1003 | | pending |
I want to get the following resultset:
- All the customers who have ordered via
WEB
or (EMPTY) but not fromPOS
- All the customers who have ordered only via
APP
Best Answer
You can use an inner join between
customers
andorders
where thevia
has the wanted values and aNOT EXISTS
to check, that no unwantedvia
exists.(If the empty
via
is actually aNULL
not an empty string, changeo1.via IN ('WEB', '')
tocoalesce(o1.via, '') IN ('WEB', '')
or too1.via = 'WEB' OR o1.via IS NULL
.)Alternatively you can do it just with
EXISTS
andNOT EXISTS
.(Again, if the empty
via
is actually aNULL
not an empty string, changeo1.via IN ('WEB', '')
tocoalesce(o1.via, '') IN ('WEB', '')
or too1.via = 'WEB' OR o1.via IS NULL
.)Again you can use a join and
NOT EXISTS
.Or just use
EXISTS
/NOT EXISTS
.