问题描述
以下请求:
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 )
返回这样的列表:
id | name
---+-----
1 | a
1 | b
2 | a
2 | y
2 | z
3 | a
3 | b
3 | c
3 | d
如何获取id
必须至少具有a
和b
的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,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']