繁体   English   中英

查询嵌套的 JSON 字段、MYSQL、PHP

[英]QUERY against nested JSON field, MYSQL, PHP

我有这样的结构:

{"placards":
    [
    {"barcode": "string", "destination":"string", "weight":"string"},
    {etc...}
]
}

存储在 MYSQL 数据库中的单个列中。

我正在尝试搜索特定的条形码,并返回该条形码位于该行中的 json 结构内的整行。

我尝试了两种方法,都在堆栈溢出时找到,但我没有在一种方法中得到结果,下面我将发布后者的错误。

attempt1:
"SELECT * FROM table WHERE placards[*->barcode] = ".$job->events[0]->imcb;


attempt2:
    $sampleBC = $job->events[0]->imcb;
        $sql = 'SELECT * FROM(
        SELECT data_column->"[*]" as row
        from table
        where $sampleBC IN JSON_EXTRACT(data_column, ""
    )
    WHERE row->".barcode" = $sampleBC';


这些方法都没有在 $stmt->error 上给出错误,但我实际上无法通过此查询成功获取任何内容。

你可以只使用json_contains()

select *
from mytable
where json_contains(data_column, '{ "barcode": "foo" }' , '$.placards')

此短语为:在路径'placards'下的数组中搜索包含候选对象'{ "barcode": "foo" }'的键/值对的任何元素,其中'foo'是条形码值你搜索。

DB Fiddle 上的演示

set @data_column = 
    '{
        "placards": [
            {"barcode": "foo", "destination":"string", "weight":"string"},
            {"barcode": "bar", "destination":"string", "weight":"string"}
        ]
    }';

select json_contains(@data_column, '{ "barcode": "foo" }' , '$.placards') is_a_match;
| is_a_match |
| ---------: |
|          1 |

select json_contains(@data_column, '{ "barcode": "baz" }' , '$.placards') is_a_match;

| is_a_match |
| ---------: |
|          0 |

从 MySQL 8.0.17 开始,你甚至可以在嵌套的 json 数组上创建多值索引,因此数据库不需要对这个查询执行全表扫描:

alter table mytable 
    add index myidx( (cast(data_column -> '$.placards' as unsigned array)) );

您将不得不使用 JSON_TABLE():

SELECT mytable.* FROM mytable,
  JSON_TABLE(mytable.data_column, '$.placards[*]' COLUMNS (
    barcode VARCHAR(100) PATH '$.barcode',
    destination VARCHAR(100) PATH '$.destination', 
    weight VARCHAR(20) PATH '$.weight'
  )) AS j
WHERE j.barcode = ?

如果您将这些字段存储在普通列而不是 JSON 中会简单得多。 每个标语牌存储一行, barcodedescriptionweight单独列。

SELECT m.* FROM mytable AS m JOIN placards AS p ON m.id = p.mytableid 
WHERE p.barcode = ?

我在 Stack Overflow 问题中看到的 MySQL 中 JSON 的大多数用途都是不必要的,因为数据不需要 JSON 的灵活性。 对 JSON 文档的查询很难编写,也很难优化。 JSON 还需要更多空间来存储相同的数据。

暂无
暂无

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

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