まず、 HistoricalPrices列を空の JSON 配列で初期化する必要があります。あなたはそれを行うことができますjson_array
:
UPDATE Products
SET HistoricalPrices = json_array()
WHERE HistoricalPrices IS NULL;
新しい製品を挿入するときも同じことを行う必要があります。
INSERT INTO Products (..., HistoricalPrices)
VALUES (..., json_array());
既存のレコードのHistoricalPricesに価格を追加するには、 を使用できますjson_array_append
。
たとえば、製品 ID 1 の 2016 年 5 月 1 日の履歴価格 12.34 を追加するには、次のように実行します。
UPDATE Products
SET HistoricalPrices =
json_array_append(HistoricalPrices,
'$', json_object('CreateDate', '2016-05-01', 'Price', 23.65)
)
WHERE ProductID = 1;
一度に複数の価格を追加できます。
UPDATE Products
SET HistoricalPrices =
json_array_append(HistoricalPrices,
'$', json_object('CreateDate', '2016-05-01', 'Price', 12.34),
'$', json_object('CreateDate', '2016-05-22', 'Price', 12.50)
)
WHERE ProductID = 1;
JSON 値の構造は次のようになります。
[
{
"CreateDate": "2016-05-01",
"Price": 12.34
},
{
"CreateDate": "2016-05-22",
"Price": 12.50
}
]