[英]How do I extract values from a JSON array in MariaDB or MySQL?
I have a table in a MariaDB database.我在 MariaDB 数据库中有一个表。 This table has a LONGTEXT column which is used to store a JSON array (read more about this topic in MariaDB JSON Data Type ).
此表有一个LONGTEXT列,用于存储JSON 数组(在MariaDB JSON 数据类型中阅读有关此主题的更多信息)。
I would like to extract values from the JSON array, based on a certain key.我想根据某个键从 JSON 数组中提取值。 How do I achieve this with MariaDB (or MySQL)?
如何使用 MariaDB(或 MySQL)实现此目的?
Here's the simplified table thing
(just for demo purposes):这是简化
thing
表格(仅用于演示目的):
id ![]() |
thing_name![]() |
examples![]() |
---|---|---|
0 ![]() |
fruit![]() |
[{"color": "green","title": "Apple"},{"color": "orange","title": "Orange"},{"color": "yellow","title": "Banana"}] |
1 ![]() |
car![]() |
[{"color": "silver","title": "VW"},{"color": "black","title": "Bentley"},{"color": "blue","title": "Tesla"}] |
My goal is to extract all title
values from the JSON array.我的目标是从 JSON 数组中提取所有
title
值。
You can use JSON_EXTRACT for this task (works for both MariaDB and MySQL).您可以为此任务使用JSON_EXTRACT (适用于 MariaDB 和 MySQL)。 This function also supports wildcards , as described in the docs:
这个 function 也支持wildcards ,如文档中所述:
Paths can contain * or ** wildcards
路径可以包含 * 或 ** 通配符
Depending on whether you have multiple levels of data (eg single document vs array), either a single or double asterisk wildcard should be used:根据您是否有多个级别的数据(例如单个文档或数组),应使用单个或双星号通配符:
JSON_EXTRACT(json,'$**.key')
json
is a valid JSON document (eg a column), key
is the lookup key used. json
是有效的 JSON 文档(例如列), key
是使用的查找键。
In order to find all title
values in your JSON array, use the following query:为了找到 JSON 数组中的所有
title
值,请使用以下查询:
SELECT id, thing_name, JSON_EXTRACT(examples, '$**.title') as examples_titles FROM thing
id ![]() |
thing_name![]() |
examples_titles![]() |
---|---|---|
0 ![]() |
fruit![]() |
["Apple", "Orange", "Banana"] |
1 ![]() |
car![]() |
["VW", "Bentley", "Tesla"] |
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.