Ini dimungkinkan dengan membuat ulang larik json pada setiap pembaruan.
SQL untuk pembuatan tabel dan contoh penyisipan data:
CREATE TABLE test_table(
id BIGSERIAL PRIMARY KEY ,
game TEXT,
players JSONB
);
INSERT INTO test_table(game, players)
VALUES
('chess', '[{"name": "Joe", "role": "admin"}, {"name": "Mike", "role": "user"}]'),
('football', '[{"name": "Foo", "role": "user"}, {"name": "Bar", "role": "user"}]');
Data yang dimasukkan:
+----+----------+----------------------------------------------------------------------+
| id | game | players |
+----+----------+----------------------------------------------------------------------+
| 1 | chess | [{"name": "Joe", "role": "admin"}, {"name": "Mike", "role": "user"}] |
| 2 | football | [{"name": "Foo", "role": "user"}, {"name": "Bar", "role": "user"}] |
+----+----------+----------------------------------------------------------------------+
Perbarui kueri:
WITH json_rows AS
(SELECT id, jsonb_array_elements(players) as json_data FROM test_table
WHERE game = 'chess'),
updated_rows AS (
SELECT
id,
array_to_json(array_agg(
CASE WHEN json_data -> 'name' = '"Joe"'
THEN jsonb_set(json_data, '{role}', '"user"')
ELSE json_data END)) as updated_json
FROM json_rows
GROUP BY id
)
UPDATE test_table SET players = u.updated_json
FROM updated_rows u
WHERE test_table.id = u.id;
Hasil kueri:
+----+----------+---------------------------------------------------------------------+
| id | game | players |
+----+----------+---------------------------------------------------------------------+
| 2 | football | [{"name": "Foo", "role": "user"}, {"name": "Bar", "role": "user"}] |
| 1 | chess | [{"name": "Joe", "role": "user"}, {"name": "Mike", "role": "user"}] |
+----+----------+---------------------------------------------------------------------+
Kueri bekerja dengan cara berikut:
-
Ubah array json menjadi baris json dan filter dengan
game
Properti. Ini dilakukan dengan membuatjson_rows
CTE. -
Perbarui data json di baris json tempat pengguna "Joe" ditemukan.
-
Setelah Anda memiliki nilai json baru, lakukan pembaruan berdasarkan id.
Catatan: Seperti yang Anda lihat, dalam implementasi saat ini, array json dibuat ulang (hanya di baris yang perlu diperbarui). Ini dapat menyebabkan perubahan urutan elemen di dalam array.