Postgres 将所有数组值匹配到具有和条件的同一列---更新

Postgres Match All array values to same column with and condition ---updated

我有 table table_a 以下列

id  event_id
1   101
1   102
1   103
2   105
2   103
2   106

I and to search (101, 103) with and conditions similar to query with OR condition

例如 id 1 匹配 101 和 103 event_id;

为此,我编写了以下查询,但它不起作用。

select * from table_a where event_id = ALL(ARRAY[101,103]);

已更新---------------------------- 我还有另一个问题

假设 id 与另一个 table event_categories 有这样的关系。

id      parent_id
101     null
102     101
103     101
104     null
105     104

所以我想从 table_a 中获取记录,基于 AND 与父事件类别,或在该父事件类别中。

例如 101、104 与 102、103 在 101 的 OR 之内

使用HAVING子句:

SELECT t.id 
FROM YourTable
WHERE event_id IN(101,103)
GROUP BY t.id
HAVING COUNT(distinct event_id) = 2

您需要为单个 ID 汇总所有 event_ids:

select id
from table_a
group by id
having array_agg(event_id) @> array[101,103];

@> 是包含运算符,因此它检查所有 event_ids 的数组是否包含具有这两个 ID 的数组。

这将 return 任何具有 至少 两个事件 101 和 103(这是您在问题中要求的)的 ID。

如果您想找到那些 恰好 这两个 event_ids(您的示例数据不包含)的 ID,您可以使用:

select id
from table_a
group by id
having array_agg(distinct event_id order by event_id) = array[101,103];

请注意,数组中元素的顺序对 = 运算符很重要(与 "contains" @> 运算符不同)