How to update sum of array elements in json in MySQL?



I am using mysql 8.0.22
My sample table be like

id students total_marks
1 {"students":[{"marks":100},{"marks":100},{"marks":100},{"marks":100}]}

After update it should be

id students total_marks
1 {"students":[{"marks":100},{"marks":100},{"marks":100},{"marks":100}]} 400

I ahve to add all the marks in that json. I am able to write a stored procedure for that.
I am trying to do it in one query.
How can I do it? Thanks.


Finally answering my own question.

Please refer JSON_TABLE.
JSON_TABLE() takes json, path to array and columns with path to required field and converts it to a table format. we can use that table same as other table in that query.

update sample s
set s.total_marks = (
                 select sum(t.marks)
                 from JSON_TABLE(s.students, '$.students[*]' columns(marks int path '$.marks'))
                 as temp_table t 
where = 1;

Answered By – Manonandan S K

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More