PostgreSQL 中多个数组的交集
我有一个视图定义为:
CREATE VIEW View1 AS
SELECT Field1, Field2, array_agg(Field3) AS AggField
FROM Table1
GROUP BY Field1, Field2;
我想做的是获取 AggField 中数组的交集,例如:
SELECT intersection(AggField) FROM View1 WHERE Field2 = 'SomeValue';
这是否可能,或者是否有更好的方法来实现我想要的?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我能想到的最接近数组交集的是:
这假设
a1
和a2
是具有相同类型元素的单维数组。您可以将其包装在如下所示的函数中:然后您可以执行如下操作:
请注意,这并不能保证返回数组中的任何特定顺序,但如果您关心的话,可以修复它。然后您可以创建自己的聚合函数:
现在我们明白为什么 array_intersect 使用 NULL 做一些有趣且有些混乱的事情了。我们需要一个行为类似于通用集的聚合初始值,我们可以使用 NULL (是的,这闻起来有点不对劲,但我想不出更好的办法)。
一旦所有这些都到位,您就可以做这样的事情:
不完全简单或高效,但也许是一个合理的起点,并且比什么都不做要好。
有用的参考:
array_agg
解除嵌套
The closest thing to an array intersection that I can think of is this:
This assumes that
a1
anda2
are single dimension arrays with the same type of elements. You could wrap that up in a function something like this:Then you could do things like this:
Note that this doesn't guarantee any particular order in the returned array but you can fix that if you care about it. Then you could create your own aggregate function:
And now we see why
array_intersect
does funny and somewhat kludgey things with NULLs. We need an initial value for the aggregation that behaves like the universal set and we can use NULL for that (yes, this smells a bit off but I can't think of anything better off the top of my head).Once all this is in place, you can do things like this:
Not exactly simple or efficient but maybe a reasonable starting point and better than nothing at all.
Useful references:
array_agg
unnest
接受的答案对我不起作用。我就是这样解决的。
The accepted answer did not work for me. This is how I fixed it.
现在回答这个问题有点晚了,但也许有人会需要它,所以我决定分享我写的东西,因为没有找到任何数量数组的交集的现成解决方案。所以就是这样。该函数接收数组的数组,如果它只是单个数组,函数返回第一个数组,如果有2个数组,函数与2个数组相交并返回结果,如果多于2个数组,函数取2个第一个数组的交集,并将其存储在某些变量中并循环遍历所有其他数组,将每个下一个数组与存储的结果相交并将结果存储在变量中。如果结果为 null,则它与 null 一起存在。在 和 变量中存储数组以及从函数返回的交互数据。
这是验证其工作原理的代码。
It is bit late to answer this question but maybe somebody will need it so I decided to share something I wrote cause did not found any ready solution for intersection of any number of arrays. So here it is. This function receives array of arrays, if it is only single array, function returns first array, if there are 2 arrays function intersects 2 arrays and returns result, if it is more that 2 arrays, function takes intersection of 2 first arrays, stores it in some variable and loops through all other arrays, intersect each next array with stored result and stores result in variable. if result is null it exists with null. In the and the variable that stores array with interacted data returned from the function.
Here is the code to validate it works.