如何在sqlalchemy中获得两个阵列/列表的交集
我有类似的问题与这个(最相似的是,与答案是答案&&
)。对于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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一种方法*做到这一点,将是解开数组列,然后重新聚集匹配列表值的行,分组在ID上。这可以用作子查询:
等效的SQLalchemy构造是:
返回
*可能会有更有效的方法。
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:
The equivalent SQLAlchemy construct is:
returning
* There may well be more efficient ways.