Select 来自 postgres 中的交叉表问题
Select from cross tables in postgres problem
假设我有一个 table A,其中包含 X、Y 和 Z 行,我还有另一个 table 将元素从 A 关联到另一个 table B。
- A)
ID | name
01 | X
02 | Y
03 | Z
- B)
ID | name
01 | b
- A_B)
ID | A_ID | B_ID
01 | 01 | 01
A_B : element_A, element_B, 我想查询 B returns 中的元素 b 和 A [=24= 中的所有元素 a ] 如果 table A_B 中存在 {a, b} 则为真,如果不存在则为假
Result of b in B
A.name | Value
X | True
Y | False
Z | False
OR
A.name | B.ID
X | 01
Y | null
Z | NULL
这就是我到目前为止所尝试的。
SELECT *
from A
LEFT JOIN A_B ei ON A.id = A_B.a_id
你可以cross join
tables a
和b
来生成所有可能的组合,然后带桥table a_b
left join
:
select a.name, (ab.id is not null) as is_in_ab
from a
cross join b
left join a_b ab on ab.a_id = a.id and ab.b_id = b.id
where b.name = 'b'
您还可以使用 exists
和相关的子查询:
select
a.name,
exists (select 1 from a_b ab where ab.a_id = a.id and ab.b_id = b.id) as is_in_ab
from a
cross join b
where b.name = '2'
假设我有一个 table A,其中包含 X、Y 和 Z 行,我还有另一个 table 将元素从 A 关联到另一个 table B。
- A)
ID | name
01 | X
02 | Y
03 | Z
- B)
ID | name
01 | b
- A_B)
ID | A_ID | B_ID
01 | 01 | 01
A_B : element_A, element_B, 我想查询 B returns 中的元素 b 和 A [=24= 中的所有元素 a ] 如果 table A_B 中存在 {a, b} 则为真,如果不存在则为假
Result of b in B
A.name | Value
X | True
Y | False
Z | False
OR
A.name | B.ID
X | 01
Y | null
Z | NULL
这就是我到目前为止所尝试的。
SELECT *
from A
LEFT JOIN A_B ei ON A.id = A_B.a_id
你可以cross join
tables a
和b
来生成所有可能的组合,然后带桥table a_b
left join
:
select a.name, (ab.id is not null) as is_in_ab
from a
cross join b
left join a_b ab on ab.a_id = a.id and ab.b_id = b.id
where b.name = 'b'
您还可以使用 exists
和相关的子查询:
select
a.name,
exists (select 1 from a_b ab where ab.a_id = a.id and ab.b_id = b.id) as is_in_ab
from a
cross join b
where b.name = '2'