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

How to fetch a value from the last element inside MySQL JSON document?

我正在使用 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

我想在我的 JSON Document 中找到最后一个 STEP,然后获取它的 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 

json_table() 并没有按照您的想法进行操作:它旨在对 JSON array 进行操作,而您的列包含 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

Demo on DB Fiddle:

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