PostgreSQL
 sql >> Base de données >  >> RDS >> PostgreSQL

mettre à jour plusieurs lignes dans une requête, mais l'entrée que nous attendons provient de l'objet json de plusieurs données

Vous pouvez faire une insertion en masse basée sur le document json. Vous devez reformater le document car le format indiqué dans la question est étrange et peu pratique.

Exemple de travail complet :

create table example(id int primary key, email text, last_name text, first_name text);

with jsondata(jdata) as (
    values
    (
    '[
        {"id": 1, "email": "[[email protected]]", "first_name": "John", "last_name": "Doe"},
        {"id": 2, "email": "[[email protected]]", "first_name": "Robert", "last_name": "Duncan"},
        {"id": 3, "email": "[[email protected]]", "first_name": "Ram", "last_name": "Das"},
        {"id": 4, "email": "[[email protected]]", "first_name": "Albert", "last_name": "Pinto"},
        {"id": 5, "email": "[[email protected]]", "first_name": "Robert", "last_name": "Peter"},
        {"id": 6, "email": "[[email protected]]", "first_name": "Christian", "last_name": "Lint"},
        {"id": 7, "email": "[[email protected]]", "first_name": "Mike", "last_name": "Hussey"},
        {"id": 8, "email": "[[email protected]]", "first_name": "Ralph", "last_name": "Hunter"}
    ]'::jsonb)
)

insert into example 
select (elem->>'id')::int, elem->>'email', elem->>'last_name', elem->>'first_name'
from jsondata,
jsonb_array_elements(jdata) as elem;

Le résultat :

select *
from example

 id |     email     | last_name | first_name 
----+---------------+-----------+------------
  1 | [[email protected]] | Doe       | John
  2 | [[email protected]] | Duncan    | Robert
  3 | [[email protected]] | Das       | Ram
  4 | [[email protected]] | Pinto     | Albert
  5 | [[email protected]] | Peter     | Robert
  6 | [[email protected]] | Lint      | Christian
  7 | [[email protected]] | Hussey    | Mike
  8 | [[email protected]] | Hunter    | Ralph
(8 rows)    

Si vous souhaitez mettre à jour le tableau (au lieu d'y insérer) :

with jsondata(jdata) as (
    -- values as above
)

update example set
    email = elem->>'email', 
    last_name = elem->>'last_name', 
    first_name = elem->>'first_name'
from jsondata,
jsonb_array_elements(jdata) as elem
where id = (elem->>'id')::int;