简体   繁体   English

如果表B中不存在SQL从表A中选择数据

[英]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. 我在创建SQL查询时遇到问题,如果表B的列中不存在offer_id列,则该查询将仅从表A中选择这些不同的记录。 How should I do this? 我应该怎么做?

Table A construction: 表A的构造:

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

Table B construction 表B的构造

-------------------------------------
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. 因此,基本上,我只希望从表A中选择该用户记录(如果未将其添加到表B中,表示某些操作的证明)。

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? 现在我正在从表A中选择不同的记录,如下所示,但是如何在表B中存在user_id以便不选择数据的情况下如何建立条件?

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: 但是,我怀疑您也希望user_id匹配:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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