Manonandan S K
Manonandan S K

Reputation: 652

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.

Upvotes: 1

Views: 135

Answers (1)

Manonandan S K
Manonandan S K

Reputation: 652

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 s.id = 1;

Upvotes: 1

Related Questions