如何在MySQL中的JSON数组中的元素内提取特定属性的所有值?

时间:2017-12-05 19:32:48

标签: mysql sql json mysql-json

我存储在MySQL表格列中的以下数据是" 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查询,它将返回所有"标题"值,即similar1,similar2和similar3等等

3 个答案:

答案 0 :(得分:1)

使用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搜索表达式。

答案 1 :(得分:0)

这看起来像是数据库设计问题。当您真正使用另一个表将这些结果存储为单独的列时,您似乎正在使用json列。

答案 2 :(得分:0)

您可以查询如下

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;

See working demo