Re: [postgresql-it] Un dubbio su come eseguire una query su una colonna JSON
- From: Daniele Varrazzo <piro@xxxxxxxxxxx>
- To: postgresql-it@xxxxxxxxxxxxx
- Date: Wed, 22 Oct 2014 10:12:09 +0100
On 2014-10-22 07:46, Carlos Catucci wrote:
2014-10-21 23:44 GMT+02:00 Daniele Varrazzo <piro@xxxxxxxxxxx>:
Cosa c'è che non va nell'usare json_populate_recordset oppure
json_array_elements, come suggerito qualche giorno fa?
Che non avevo visto i tuoi post, non so come mai. Pardonez moi e
grazie.
Se ti definisci una funzione aggiuntiva, che dato un array json estrae
un attributo da tutti gli elementi e li mette in un array postgres:
create function getall(data json, attr text) returns json[]
as $$
select array_agg(i->$2) from json_array_elements($1) i
$$ language sql immutable strict;
la puoi usare altri costrutti postgres per evitare le sottoquery, come
=any >all ecc.
select id from mydata where 1 = any(getall(data -> 'A' -> 'B',
'C')::text[]::int[]);
Puoi aggiungere zucchero sintattico creando ad es. un operatore *-> che
faccia come -> ma su un array, *->> analogo a ->> ecc. per cui la query
potrebbe diventare (non testato):
select id from mydata where 1 = any((data -> 'A' -> 'B' *->>
'C')::int[]);
che credo sia espressivo piu' o meno quanto ti aspettavi dovesse essere.
-- Daniele
Other related posts: