如何提取 MySQL 中 JSON 数组中元素内特定属性的所有值?
How can I extract all values of a particular attribute within elements inside a JSON array in MySQL?
我将以下数据存储在 MySQL table 的列中,该列属于 "json" 数据类型 (MySQL v5.7.9)
[{"id": "26", "title": "similar1", "score": "0.97"}, {"id": "27", "title": "similar2", "score": "0.87"}, {"id": "28", "title": "similar2", "score": "0.87"}]
我需要一个 MySQL 查询,它将 return 我所有的 "title" 值,即 similar1、similar2 和 similar3 等等
这看起来像是数据库设计问题。似乎您使用的是 json 列,而实际上您应该使用另一个 table 将这些结果存储为单独的列。
您可以像下面这样查询
create table testTableforus (datapoint json);
insert into testTableforus
values
('{"id": "26", "title": "similar1", "score": "0.97"}'),
('{"id": "27", "title": "similar2", "score": "0.87"}'),
('{"id": "28", "title": "similar2", "score": "0.87"}');
select datapoint->"$.title" from testTableforus;
drop table testTableforus;
使用JSON_EXTRACT()。
mysql> create table t ( j json );
mysql> insert into t set j = '[{"id": "26", "title": "similar1", "score": "0.97"}, {"id": "27", "title": "similar2", "score": "0.87"}, {"id": "28", "title": "similar2", "score": "0.87"}]';
mysql> select json_extract(j, '$[*].title') from t;
+--------------------------------------+
| json_extract(j, '$[*].title') |
+--------------------------------------+
| ["similar1", "similar2", "similar2"] |
+--------------------------------------+
如果您想在 MySQL 中使用 JSON 数据,您应该阅读 Functions that Search JSON Values 上的文档,并学习使用 JSON 搜索表达式。
我将以下数据存储在 MySQL table 的列中,该列属于 "json" 数据类型 (MySQL v5.7.9)
[{"id": "26", "title": "similar1", "score": "0.97"}, {"id": "27", "title": "similar2", "score": "0.87"}, {"id": "28", "title": "similar2", "score": "0.87"}]
我需要一个 MySQL 查询,它将 return 我所有的 "title" 值,即 similar1、similar2 和 similar3 等等
这看起来像是数据库设计问题。似乎您使用的是 json 列,而实际上您应该使用另一个 table 将这些结果存储为单独的列。
您可以像下面这样查询
create table testTableforus (datapoint json);
insert into testTableforus
values
('{"id": "26", "title": "similar1", "score": "0.97"}'),
('{"id": "27", "title": "similar2", "score": "0.87"}'),
('{"id": "28", "title": "similar2", "score": "0.87"}');
select datapoint->"$.title" from testTableforus;
drop table testTableforus;
使用JSON_EXTRACT()。
mysql> create table t ( j json );
mysql> insert into t set j = '[{"id": "26", "title": "similar1", "score": "0.97"}, {"id": "27", "title": "similar2", "score": "0.87"}, {"id": "28", "title": "similar2", "score": "0.87"}]';
mysql> select json_extract(j, '$[*].title') from t;
+--------------------------------------+
| json_extract(j, '$[*].title') |
+--------------------------------------+
| ["similar1", "similar2", "similar2"] |
+--------------------------------------+
如果您想在 MySQL 中使用 JSON 数据,您应该阅读 Functions that Search JSON Values 上的文档,并学习使用 JSON 搜索表达式。