postgresql 如何在sqlalchemy中求两个数组/列表的交集

wljmcqd8  于 2023-02-08  发布在  PostgreSQL
关注(0)|答案(1)|浏览(238)

我有类似的问题this one(最相似的是&&的答案).对于postgres,我想得到数组列和python列表的交集.我试着用&&操作符做到这一点:

query(Table.array_column.op('&&')(cast(['a', 'b'], ARRAY(Unicode)))).filter(Table.array_column.op('&&')(cast(['a', 'b'], ARRAY(Unicode))))

但是op('&&')似乎返回bool类型(对filter有意义),而不是交集。
因此,对于表数据:

id   |   array_column
1        {'7', 'xyz', 'a'}
2        {'b', 'c', 'd'}
3        {'x', 'y', 'ab'}
4        {'ab', 'ba', ''}
5        {'a', 'b', 'ab'}

我想得到:

id   |   array_column
1        {'a'}
2        {'b'}
5        {'a', 'b'}
bakd9h0s

bakd9h0s1#

一种方法 * 是取消嵌套数组列,然后重新聚合与列表值匹配的行,按id分组。这可以作为子查询来完成:

select id, array_agg(un) 
  from (select id, unnest(array_column) as un from tbl) t
  where un in ('a', 'b') 
  group by id 
  order by id;

等效的SQLAlchemy构造为:

subq = sa.select(
    tbl.c.id, sa.func.unnest(tbl.c.array_column).label('col')
).subquery('s')
stmt = (
    sa.select(subq.c.id, sa.func.array_agg(subq.c.col))
    .where(subq.c.col.in_(['a', 'b']))
    .group_by(subq.c.id)
    .order_by(subq.c.id)
)

返回

(1, ['a'])
(2, ['b'])
(5, ['a', 'b'])
  • 很可能还有更有效的方法。

相关问题