从postgres问题中的交叉表中选择

问题描述

让我们想象一下,我有一个表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个表ab来生成所有可能的组合,然后将桥表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'

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...