![](/img/trans.png)
[英]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.