我的 Postgres 表架构有两个字段:
items
,其中包含一个(整数)项目 ID 数组。如果相同的 ID 在数组中出现两次,则将其视为主要项。
primary_items
,我刚刚添加到架构中的另一个(整数)项目 ID 数组,因此它目前在所有行中都是空的。
我需要做的是:对于每一行,检查 items
中是否有重复的 ID,如果有,则将每个重复的 ID 中的一个放入 primary_items
字段。
知道如何通过查询来解决这个问题吗?理想情况下,我不必编写帮助程序 (Nodejs) 来执行此操作,但如果需要我可以。
例子:
当前:
documents_table
items primary_items
------------ -----------
{1, 2, 2, 4} {}
{1, 2, 3} {}
{3, 3} {}
{5, 4, 5, 4} {}
期望:
documents_table
items primary_items
------------ -----------
{1, 2, 2, 4} {2}
{1, 2, 3} {}
{3, 3} {3}
{5, 4, 5, 4} {5,4}
最佳答案
您可以使用这个简单的查询找到重复的元素:
select array_agg(item)
from (
select item
from unnest('{5, 4, 5, 4}'::int[]) as item
group by item
having count(*) > 1
) s
array_agg
-----------
{4,5}
(1 row)
在函数中使用查询:
create or replace function find_primary_items(arr anyarray)
returns anyarray language sql immutable
as $$
select array_agg(item)
from (
select item
from unnest(arr) as item
group by item
having count(*) > 1
) s
$$;
现在更新真的很简单:
update documents_table
set primary_items = coalesce(find_primary_items(items), '{}')
returning *;
items | primary_items
-----------+---------------
{1,2,2,4} | {2}
{1,2,3} | {}
{3,3} | {3}
{5,4,5,4} | {4,5}
(4 rows)
关于postgresql - 在 Postgres 数组中查找重复项,并另存为不同的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47340495/