在 psql 中连接三个表并根据组成员资格保留结果

joinging three tables in psql and keeping results according to group membership

我正在使用 psql 并加入了来自 table A 的三个 tables A、B 和 C。

例如结果table如下:

+----+------+------+------+
| pk | a_id | b_id | c_id |
+----+------+------+------+
|  1 |    5 |   12 |   16 |
|  2 |    5 |    7 |    8 |
|  3 |    5 |    6 |   21 |
|  4 |    8 |   12 |   16 |
|  5 |    8 |    3 |    9 |
|  6 |    9 |   11 |   32 |
|  7 |    9 |    8 |    2 |
+----+------+------+------+

我正在尝试在 a_id 上建立 c_id 关系。在 a_id 中有三组 [5,8,9]。例如 c_id=16 与 a_id=[5,8] 有关系,所以 c_id=[8,21,9,32] 必须通过 a_id 保护=[5,8]。结果 table 应该如下所示:

+----+------+------+------+
| pk | a_id | b_id | c_id |
+----+------+------+------+
|  1 |    5 |   12 |   16 |
|  2 |    5 |    7 |    8 |
|  3 |    5 |    6 |   21 |
|  4 |    8 |   12 |   16 |
|  5 |    8 |    3 |    9 |
+----+------+------+------+

如何在连接语句中写这样的条件?

加入后,您可以编写此查询。我直接创建了你的结果 table,然后我写了一个 SQL 查询。

SELECT * from res
WHERE a_id in (SELECT distinct a_id
               FROM res
               WHERE c_id=16)