简体   繁体   中英

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

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
                 );

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