如何实现 json 数据类型来存储价格历史
How to implement json datatype to store price history
我在 MySQL (5.7.10) 中有一个 "Products" table,其中包含许多产品。
我想在 "Products" table 中包含一个名为 HistoricalPrices 的字段,使用 JSON 数据类型。
例如 "Products" table 包括以下内容:
ProductID
ProductName
ProductDesc
CreateDate
Price
HistoricalPrices (json) NEW
HistoricalPrice 应在 json 中包含 "CreateDate" 和 "Price" 键,因此我可以添加多个价格变化。
我更喜欢这种方法(而不是为每个价格历史记录添加新行),因为我只需要这些价格来报告。
我正在寻找的是 MySQL 在 HistoricalPrice 字段中添加新价格变化的查询 (json)
您应该首先使用空 JSON 数组初始化 HistoricalPrices 列。您可以使用 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-05-01 的历史价格 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
}
]
我在 MySQL (5.7.10) 中有一个 "Products" table,其中包含许多产品。 我想在 "Products" table 中包含一个名为 HistoricalPrices 的字段,使用 JSON 数据类型。
例如 "Products" table 包括以下内容:
ProductID
ProductName
ProductDesc
CreateDate
Price
HistoricalPrices (json) NEW
HistoricalPrice 应在 json 中包含 "CreateDate" 和 "Price" 键,因此我可以添加多个价格变化。
我更喜欢这种方法(而不是为每个价格历史记录添加新行),因为我只需要这些价格来报告。
我正在寻找的是 MySQL 在 HistoricalPrice 字段中添加新价格变化的查询 (json)
您应该首先使用空 JSON 数组初始化 HistoricalPrices 列。您可以使用 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-05-01 的历史价格 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
}
]