【问题标题】:How to get intersection of two arrays/lists in sqlalchemy如何在 sqlalchemy 中获取两个数组/列表的交集
【发布时间】:2023-02-04 20:37:00
【问题描述】:

我有与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 类型(对过滤器有意义)而不是交集。

所以对于表数据:

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

【问题讨论】:

    标签: python postgresql sqlalchemy


    【解决方案1】:

    单程*这样做是取消嵌套数组列,然后重新聚合与列表值匹配的行,按 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'])
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-29
      • 1970-01-01
      相关资源
      最近更新 更多