[英]Select rows with specific value in JSON column
I have a column in MySQL
which has an array of JSON with multi objects, this is one of its values:我在MySQL
中有一个列,其中包含一个包含多个对象的 JSON 数组,这是它的值之一:
[
{
"date": "2014-01-17T00:00:00.000Z",
"price": "56.89845204047926330304107978008687496185302734375",
"total": "105774.2223432509504803533673",
"amount": 1859,
"symbol": "fb",
"transaction_code": "buy"
},
{
"date": "2015-04-20T00:00:00.000Z",
"price": "121.497274059658224132363102398812770843505859375",
"total": "962865.8969227914262489775865",
"amount": 7925,
"symbol": "aapl",
"transaction_code": "buy"
},
{
"date": "2013-11-06T00:00:00.000Z",
"price": "49.18047492858931235559794004075229167938232421875",
"total": "330738.6938947631255913961468",
"amount": 6725,
"symbol": "fb",
"transaction_code": "sell"
}
]
I want to extract objects with "transaction_code": "sell"
and find the average price of them.我想用"transaction_code": "sell"
提取对象并找到它们的平均价格。
In MySQL 8.0, you can use the JSON_TABLE() function to transform the data so you can apply a WHERE clause to it.在 MySQL 8.0 中,您可以使用 JSON_TABLE() function 来转换数据,以便您可以对其应用 WHERE 子句。
SELECT AVG(j.price)
FROM mytable CROSS JOIN JSON_TABLE(mytable.example_json, '$[*]' COLUMNS(
date DATETIME PATH '$.date',
price DOUBLE PATH '$.price',
total DOUBLE PATH '$.total',
amount INT PATH '$.amount',
symbol VARCHAR(10) PATH '$.symbol',
transaction_code VARCHAR(10) PATH '$.transaction_code'
)
) AS j
WHERE j.transaction_code = 'sell';
This works all right, but it will be bound to have poor performance, and it's more work to write the code every time you want to do this.这样可以,但是必然性能很差,而且每次要这样写代码的工作量就比较大。
In versions of MySQL before 8.0, you're out of luck.在 8.0 之前的 MySQL 版本中,您不走运。 Fetch the whole JSON document into a client application, deserialize it into a data structure, and write custom code to loop over it.将整个 JSON 文档获取到客户端应用程序中,将其反序列化为数据结构,然后编写自定义代码以对其进行循环。
It would be better to talk to whomever decided to use JSON to store this data, and convince them to use normal rows and columns.最好与决定使用 JSON 存储这些数据的人交谈,并说服他们使用普通的行和列。 The queries will be easier, and you can create indexes to optimize them.查询会更容易,您可以创建索引来优化它们。
Also use the DECIMAL type for currency values, not DOUBLE.货币值也使用 DECIMAL 类型,而不是 DOUBLE。 No one wants to make exact change for 56.89845204047926330304107978008687496185302734375!没有人愿意为 56.89845204047926330304107978008687496185302734375 做出确切的改变!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.