[英]Oracle SQL Converting Rows into Columns and Giving them Values from another Table based on Conditions from another Table
[英]SQL: select rows from a certain table based on conditions in this and another table
我有两个表在 postgresql 上共享 ID。
我想 select 表 A 中的某些行,基于条件 Y(在表 A 中)和基于条件 Z 在不同的表 (B) 中)。 例如:
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
ID 必须是唯一的 - 相同的 ID 在每个表中只能出现一次,如果两个表中的 ID 相同,则表示两者都引用相同的 object。
使用 SQL 查询,我想找到所有情况:
1 - 两个表中存在相同的 ID
2 - 类型为 F
3 - 日期在 2021 年 12 月 31 日之后
同样,只会返回表 A 中的行。
所以唯一返回的行应该是: 1 F
有点难以理解您实际面临的问题,因为这是非常基本的 SQL。
使用EXISTS
:
select *
from a
where type = 'F'
and exists (select null from b where b.id = a.id and dt >= date '2022-01-01');
或IN
:
select *
from a
where type = 'F'
and id in (select id from b where dt >= date '2022-01-01');
或者,由于两个表中的 ID 都是唯一的,因此加入:
select a.*
from a
join b on b.id = a.id
where a.type = 'F'
and b.dt >= date '2022-01-01';
这里我最喜欢的是IN
子句,因为你想要 select 表 A 中满足条件的数据。 所以不需要连接,只需要一个 where 子句,并且IN
比EXISTS
更容易阅读。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.