简体   繁体   English

SQL:select 来自某个表的行,基于此表和另一个表中的条件

[英]SQL: select rows from a certain table based on conditions in this and another table

I have two tables that share IDs on a postgresql.我有两个表在 postgresql 上共享 ID。
I would like to select certain rows from table A, based on condition Y (in table A) AND based on Condition Z in a different table (B) ).我想 select 表 A 中的某些行,基于条件 Y(在表 A 中)和基于条件 Z 在不同的表 (B) 中)。 For example:例如:

Table A                  Table B
ID  |  type             ID  |  date
0      E                1      01.01.2022
1      F                2      01.01.2022 
2      E                3      01.01.2010
3      F

IDs MUST by unique - the same ID can appear only once in each table, and if the same ID is in both tables it means that both are referring to the same object. ID 必须是唯一的 - 相同的 ID 在每个表中只能出现一次,如果两个表中的 ID 相同,则表示两者都引用相同的 object。
Using an SQL query, I would like to find all cases where:使用 SQL 查询,我想找到所有情况:
1 - the same ID exists in both tables 1 - 两个表中存在相同的 ID
2 - type is F 2 - 类型为 F
3 - date is after 31.12.2021 3 - 日期在 2021 年 12 月 31 日之后
And again, only rows from table A will be returned.同样,只会返回表 A 中的行。
So the only returned row should be: 1 F所以唯一返回的行应该是: 1 F

It is a bit hard t understand what problem you are actually facing, as this is very basic SQL.有点难以理解您实际面临的问题,因为这是非常基本的 SQL。

Use EXISTS :使用EXISTS

select *
from a
where type = 'F'
and exists (select null from b where b.id = a.id and dt >= date '2022-01-01');

Or IN :IN

select *
from a
where type = 'F'
and id in (select id from b where dt >= date '2022-01-01');

Or, as the IDs are unique in both tables, join:或者,由于两个表中的 ID 都是唯一的,因此加入:

select a.*
from a
join b on b.id = a.id
where a.type = 'F'
and b.dt >= date '2022-01-01';

My favorite here is the IN clause, because you want to select data from table A where conditions are met.这里我最喜欢的是IN子句,因为你想要 select 表 A 中满足条件的数据。 So no join needed, just a where clause, and IN is easier to read than EXISTS .所以不需要连接,只需要一个 where 子句,并且INEXISTS更容易阅读。

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

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