问题描述
让我们想象一下,我有一个表A,其中包含X,Y和Z行,而我还有另一个表,该表将A中的元素与另一个表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中的元素b对于A中的所有元素都返回a,如果{a,b}存在于表A_B中则返回True,否则返回False
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
个表a
和b
来生成所有可能的组合,然后将桥表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'