如何使用 PostgreSQL 查询给定列至少与给定数组中的所有值匹配的所有行?

How to query all rows where a given column matches at least all the values in a given array with PostgreSQL?

请求如下:

SELECT foos.id,bars.name
FROM foos
JOIN bar_foo ON (bar_foo.foo_id = id )
JOIN bars ON (bars.id = bar_foo.bar_id )

returns 这样的列表:

id | name
---+-----
 1 | a
 1 | b
 2 | a
 2 | y
 2 | z
 3 | a
 3 | b
 3 | c
 3 | d

如何获取 id 必须至少具有 ab 的 ID,以及更一般的给定数组的内容?

从上面的例子中,我会得到:

id | name
---+-----
 1 | a
 1 | b
 3 | a
 3 | b
 3 | c
 3 | d

对于两个值,您可以使用窗口布尔聚合:

select *
from (
    select f.id, b.name, 
        bool_or(b.name = 'a') over(partition by id) has_a,
        bool_or(b.name = 'b') over(partition by id) has_b
    from foos f
    join bar_foo bf on bf.foo_id = f.id
    join bars b on b.id = bf.bar_id
) t
where has_a and has_b

更通用的方法是使用数组聚合:

select *
from (
    select f.id, b.name, 
        array_agg(b.name) over(partition by id) arr_names
    from foos f
    join bar_foo bf on bf.foo_id = f.id
    join bars b on b.id = bf.bar_id
) t
where arr_names @> array['a', 'b']