如何在sqlalchemy中获得两个阵列/列表的交集

发布于 2025-02-13 22:33:49 字数 878 浏览 1 评论 0原文

我有类似的问题与这个(最相似的是,与答案是答案&&)。对于Postgres,我想获得数组列和Python列表的交集。我尝试使用&&运算符来做到这一点:

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

但是看来op('&&') return> return bool类型(对滤波器具有感知)而不是交叉点。

因此,对于表数据:

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'}

I have similar problem to this one (most similar is the answer with &&). For postgres, I would like to get the intersection of array column and python list. I've tried to do that with && operator:

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

but it seems that op('&&') return bool type (what has sense for filter) not the intersection.

So for table data:

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

I would like to get:

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

寄人书 2025-02-20 22:33:49

一种方法*做到这一点,将是解开数组列,然后重新聚集匹配列表值的行,分组在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'])

*可能会有更有效的方法。

One way* to do this would be to unnest the array column, and then re-aggregate the rows that match the list values, grouping on id. This could be done as a subquery:

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;

The equivalent SQLAlchemy construct is:

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)
)

returning

(1, ['a'])
(2, ['b'])
(5, ['a', 'b'])

* There may well be more efficient ways.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文