【问题标题】:How can I extract all values of a particular attribute within elements inside a JSON array in MySQL?如何在 MySQL 中的 JSON 数组内的元素中提取特定属性的所有值?
【发布时间】:2018-05-19 13:37:08
【问题描述】:

我将以下数据存储在“json”数据类型的 MySQL 表列中(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 查询,它将返回所有“标题”值,即相似 1、相似 2 和相似 3 等等

【问题讨论】:

    标签: mysql sql json mysql-json


    【解决方案1】:

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

    【讨论】:

    • 我最初的数据库设计确实在多列中包含所有值,但这是我正在处理的一对多数据库关系。所以,如果我开始将“id”、“title”和“score”保存在单独的列中,并且它们有很多多个值,我最终会将它们保存在太多行中
    【解决方案2】:

    你可以像下面这样查询

    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

    【讨论】:

    • 谢谢bhai,但如果您仔细观察,我将所有数据都放在一条记录中,而不是多行。基本上我的数据是一个 JSON 对象数组,而不是像您演示的那样单个 JSON 对象
    【解决方案3】:

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

    【讨论】:

    • 非常感谢比尔,你拯救了我的一天。 '$[*].title' 是我要找的。我确实浏览了文档,但无法弄清楚如何在 JSON 数组上使用它
    • 嘿,比尔,还记得你不久前告诉我的话吗? ;-)
    • @Fred-ii- 你找到我了!我正在打破自己的规则。但至少这不是我第 1000 次看到这个问题。
    • @BillKarwin 呵呵,比尔不用担心。也有例外 ;-) 但是是的,我抓住了你 lol! - 干杯。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-06
    • 2022-06-11
    相关资源
    最近更新 更多