如何从mysql json文档中的最后一个元素获取值?

2ic8powd  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(388)

我使用的是mysql版本 8.0.18-commercial 我的mysql查询正在返回 JSON Document 对于列值之一。

ServerName      Status
abc.com         JSON Document(as shown below)

这个 Status 列类似如下:

{
  "STEP1": {
    "state": "STARTED",
    "startTime": "2020-08-05T04:40:45.021Z"
  },
  ....
  ....
  "STEP4": {
    "state": "ENDED",
    "startTime": "2020-08-05T05:08:36.286Z"
  }
}

期望输出:

ServerName      Status
abc.com         ENDED

我要找到最后一个 STEP 在我的 JSON Document 然后拿到 state 它的价值。
我已经编写了以下查询,但它不是最后显示的 state 价值:

SELECT ServerName,
  (SELECT j.state
   FROM table t1
   CROSS JOIN json_table(Status, '$[*]' columns (state varchar(1000) PATH '$.state', startTime varchar(100) PATH '$.startTime')) j
   WHERE t1.id = t.id
   ORDER BY row_number() OVER (
                               ORDER BY j.startTime) DESC
   LIMIT 1) AS Status
FROM table AS t
yzckvree

yzckvree1#

json_table() 不做您在这里所想的:它意味着在一个json数组上操作,而您的列包含一个json对象。
另一种方法是 json_table()json_keys() 将对象键提取为行:然后可以提取相应的值,对具有相同值的行进行排序 servername ,并仅保留每组的第一行:

select servername, state, starttime
from (
    select 
        t.servername,
        json_unquote(json_extract(t.status, concat('$.', j.k, '.startTime'))) starttime,
        json_unquote(json_extract(t.status, concat('$.', j.k, '.state'))) state,
        row_number() over(
            partition by t.servername 
            order by json_unquote(json_extract(t.status, concat('$.', j.k, '.startTime'))) desc
        ) rn
    from mytable t
    cross join json_table(
        json_keys(t.status), 
        '$[*]' columns (k varchar(50) path '$')
    ) j
) t
where rn = 1

db小提琴演示:

servername | state | starttime               
:--------- | :---- | :-----------------------
abc.com    | ENDED | 2020-08-05T05:08:36.286Z

相关问题