How can I do a left join but with two clauses
-
24-12-2019 - |
Question
I have two tables called listings
and listings_queue
. They are identical in structure. The idea is that records get put in the queue, stuff is done to them, and then they're moved to listings
.
I want to run a query that pulls any record that exists in listings
but not in listings_queue
. The criteria for not existing is that it doesn't have the field mls_listing_id and mls_id that match any in listings_queue
.
In plain english, "Give me any record in listings
that doesn't have a record in listings_queue
with the same mls_id AND mls_listing_id.
I've tried doing where clauses but can't get it to work.
Solution
Here is a way you can do this with a where
clause:
select l.*
from listings l
where not exists (select 1
from listings_queue lq
where lq.mis_id = l.mis_id and lq.mis_listing_id = l.mis_listing_id
);
You can also do this as a left outer join:
select l.*
from listings l left outer join
listings_queue lq
on lq.mis_id = l.mis_id and lq.mis_listing_id = l.mis_listing_id
where lq.mis_id is null;
This could produce duplicates if the listings_queue
table has multiple matches.