1

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.

1
  • I had miss the incremental id column. I have updated in the question. Commented Sep 20, 2021 at 14:24

1 Answer 1

1

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;
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.