首页 > 解决方案 > 我如何在我的 sql 表中读取这种类型的 json 对象

问题描述

在此处输入图像描述

我在 mysql 表中有这种类型的 json 数据。我怎样才能读到它们

[
    {
        "price": "1000",
        "itemcode": "1",
        "itemname": "Break Pads",
        "quantity": "1"
    },
    {
        "price": "800",
        "itemcode": "3",
        "itemname": "Break Oil",
        "quantity": "1"
    }
]

标签: mysqlsqljsonselectmysql-5.7

解决方案


在 MySQL 5.7 中,whereJSON_TABLE()不可用,典型的解决方案是使用数字表。

select
    d.*,
    json_unquote(json_extract(
        d.items,
        concat('$[', n.i, '].price')
    )) price,
    json_unquote(json_extract(
        d.items,
        concat('$[', n.i, '].itemcode')
    )) itemcode,
    json_unquote(json_extract(
        d.items,
        concat('$[', n.i, '].itemname')
    )) itemname,
    json_unquote(json_extract(
        d.items,
        concat('$[', n.i, '].quantity')
    )) quantity
from deals d
inner join (
    select 0 i 
    union all select 1
    union all select 2
    union all select 3
) n
    on n.i < json_length(d.items)

这将处理每个数组最多 4 个对象。如果需要更多,可以使用 more 扩展子查询union all


推荐阅读