Marcin
Marcin

Reputation: 1034

SQL select data from table A if not exists in table B

I have a problem creating the SQL query which will select only these distinct records from table A if offer_id column in table A doesnt exists in table B column. How should I do this?

Table A construction:

--------------------------
id  |  offer_id  | user_id
--------------------------

Table B construction

-------------------------------------
id  |  offer_id  | user_id | date
-------------------------------------

So basically I want only select this users records from table A if they were not added to the table B which represents the prove of some action.

Right now I'm selecting distinct records from table A like below but how to make a condition if user_id exists in table B so the data would not be selected?

SELECT DISTINCT offer_id FROM aukcje_licytacja_historia WHERE user_id = :user_id ORDER BY offer_id DESC

Upvotes: 1

Views: 2517

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1271023

You have pretty much described the solution:

select a.*
from a
where not exists (select 1 from b where b.offer_id = a.offer_id);

However, I suspect that you also want user_id to match:

select a.*
from a
where not exists (select 1
                  from b
                  where b.offer_id = a.offer_id and
                        b.user_id = a.user_id
                 );

Upvotes: 2

Related Questions