mil*_*hov 3 arrays postgresql json jsonb
在 PostgreSQL 9.4 中,我有一个这样的表:
id | array_json
---+----------------------------
1 | [{"type": "single", "field_id": 9},
| {"type": "range", "field_id": 2}, ...]
|
2 | [{"type": "single", "field_id": 10},
| {"type": "range", "field_id": 2}, ...]
...
Run Code Online (Sandbox Code Playgroud)
我想在所有 table中获取 array_json 列中所有field_id值的交集。
| field_id intersection
+-------
| 2
Run Code Online (Sandbox Code Playgroud)
我的意思是:
1.映射第一行的 field_id 值:[9, 2]
2.映射第二行的 field_id 值:[10, 2]
n. 映射 field_id 值n ...
...
最后的。获取所有行的交集:[2](假设表只有两行)
谁能告诉我如何做到这一点?
提前谢谢了
您将需要一个聚合来将连续行中的数组相交:
create or replace function array_intersect(anyarray, anyarray)
returns anyarray language sql
as $$
select
case
when $1 is null then $2
when $2 is null then $1
else
array(
select unnest($1)
intersect
select unnest($2))
end;
$$;
create aggregate array_intersect_agg (anyarray)
(
sfunc = array_intersect,
stype = anyarray
);
Run Code Online (Sandbox Code Playgroud)
使用jsonb_array_elements()witharray_agg()以field_ids整数数组的形式检索:
select id, array_agg(field_id) field_ids
from (
select id, (e->>'field_id')::int field_id
from a_table, jsonb_array_elements(array_json) e
) sub
group by 1
order by 1;
id | field_ids
----+-----------
1 | {9,2}
2 | {10,2}
(2 rows)
Run Code Online (Sandbox Code Playgroud)
使用定义的交集聚合来交叉所有行的数组:
select array_intersect_agg(field_ids)
from (
select id, array_agg(field_id) field_ids
from (
select id, (e->>'field_id')::int field_id
from a_table, jsonb_array_elements(array_json) e
) sub
group by 1
order by 1
) sub;
array_intersect_agg
---------------------
{2}
(1 row)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1569 次 |
| 最近记录: |