简体   繁体   English

如何从 MariaDB 或 MySQL 中的 JSON 数组中提取值?

[英]How do I extract values from a JSON array in MariaDB or MySQL?

Situation情况

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 数据类型中阅读有关此主题的更多信息)。

Question问题

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)实现此目的?

Example例子

Here's the simplified table thing (just for demo purposes):这是简化thing表格(仅用于演示目的):

id ID thing_name事物名称 examples例子
0 0 fruit水果 [{"color": "green","title": "Apple"},{"color": "orange","title": "Orange"},{"color": "yellow","title": "Banana"}]
1 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是使用的查找键。

For your example对于你的例子

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 ID thing_name事物名称 examples_titles例子标题
0 0 fruit水果 ["Apple", "Orange", "Banana"]
1 1个 car ["VW", "Bentley", "Tesla"]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM