MariaDB中JSON_SET无通配符时更新JSON数组指定元素的方案
Solution for Updating Specific JSON Array Entry Without Wildcard Support
Got it, since JSON_SET doesn't support wildcard paths for targeting array elements directly, we can use a combination of MySQL's JSON functions to unpack the array, modify the specific entry, then repack it back into the JSON structure. Here's a practical implementation tailored to your scenario:
Full Update Query
UPDATE table_name t JOIN ( SELECT id, JSON_ARRAYAGG( CASE WHEN j.student_id = '5' THEN JSON_SET(j.student, '$.name', 'bbb') ELSE j.student END ) AS updated_student_array FROM table_name, JSON_TABLE( class, '$.student[*]' COLUMNS ( student JSON PATH '$', student_id VARCHAR(10) PATH '$.student_id' ) ) j -- Uncomment this line if you only want to update a specific row (e.g., id=1) -- WHERE t.id = 1 GROUP BY id ) jt ON t.id = jt.id SET t.class = JSON_SET(t.class, '$.student', jt.updated_student_array);
How This Works
Let's break down each part to make it clear:
JSON_TABLE: This function unpacks thestudentarray from theclassJSON column into a relational table-like structure. We extract both the fullstudentJSON object and thestudent_idvalue to pinpoint which entry needs updating.CASEStatement: For each unpacked student entry, we check if thestudent_idmatches '5'. If it does, we useJSON_SETto overwrite thenamefield with 'bbb'; otherwise, we keep the original student object unchanged.JSON_ARRAYAGG: This aggregates all the (modified or original) student objects back into a single JSON array, ready to replace the original array.- JOIN & UPDATE: We join the original table with our subquery result, then use
JSON_SETto swap out the oldstudentarray in theclasscolumn with our updated version.
Quick Notes
- This requires MySQL 8.0 or newer since
JSON_TABLEwas introduced in that release. - If you need to update all rows in the table (not just a specific id), remove the
WHERE t.id = 1clause from the subquery. - Double-check that the data type for
student_idinJSON_TABLEmatches your actual data (in your example it's a string '5', so we useVARCHAR).
内容的提问来源于stack exchange,提问作者pvjhs
相关产品推荐
相关产品推荐

