0

The Mysql version is 8.0.18-commercial I have written the following query which displays results from details column

select details from table t1;

Output:
[
  {
    "Msg": "Job Running",
    "Task": "IN_PROGRESS",
    "Date": "2020-07-20 16:25:15",
  },
  {
    "Msg": "Job failed",
    "Task": "IN_PROGRESS",
    "Date": "2020-07-20 16:35:24",
  }
]

I want the Msg value only from the last element which has latest Date

My desired output is displaying Msg of the element with latest date :

ColumnName      ColumnValue
Msg             Job failed

I have written following query but it is giving null output

select details->>"$.Msg" from table t1;
5
  • So stackoverflow.com/questions/39906435/… for how to convert a JSON array to rows. Then you can use stackoverflow.com/questions/7745609/… to get the row with the latest value. Commented Jul 20, 2020 at 22:02
  • Do you want the message of the last array element, or of the element with latest date? Commented Jul 20, 2020 at 22:06
  • I want msg of the element with latest date Commented Jul 20, 2020 at 22:07
  • Out of curiosity, why did you store this as JSON? It would have been easier if you had stored this in a normal manner, with each array member on a row, and each object field in a normal column. In most cases, using JSON for structure data like this makes it harder to query data in an SQL database. Commented Jul 20, 2020 at 22:29
  • I am migrating data from mongo collection and it can be migrated in the form of JSON documents Commented Jul 20, 2020 at 22:39

1 Answer 1

1

If you are running MySQ. 8.0, you can use json_table() to unnest the json array to rows, then row_number() to keep the latest record per original row.

Assuming that the primary key of your table is id, you would phrase this as:

select msg, activity_date
from (
    select x.*, row_number() over(partition by t.id order by x.activity_date desc) rn
    from mytable t
    cross join json_table(
        t.details,
        '$[*]' columns(
            msg varchar(50) path '$.Msg',
            activity_date datetime path '$.activityDate'
        )
    ) x
) t
where rn = 1

Demo on DB Fiddle:

msg        | activity_date      
:--------- | :------------------
Job failed | 2020-07-20 16:35:24
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.