Querying a Nested JSON Array by Key
In MySQL, you can retrieve specific values from a nested JSON array using a combination of the JSON_TABLE() function and a WHERE clause.
Consider the following JSON array:
<code class="json">[ {"Race": "Orc", "strength": 14}, {"Race": "Knight", "strength": 7} ]</code>
To retrieve the strength of the Knight, you can use the following query:
<code class="sql">SELECT j.strength FROM mytable, JSON_TABLE(mycol, '$[*]' COLUMNS ( race VARCHAR(10) PATH '$.Race', strength INT PATH '$.strength' )) AS j WHERE j.race = 'Knight'</code>
This query uses the JSON_TABLE() function to create a virtual table from the JSON array, with columns for each attribute. The WHERE clause is then used to filter the results based on the "Race" attribute.
Benefits and Limitations
Using JSON_TABLE() offers several benefits:
However, it also has some limitations:
Alternative Approach
If the data structure is unknown or changes frequently, an alternative approach is to use the JSON_SEARCH() function to find the path to the desired value, and then use the path operator to extract the value. However, this method does not allow for selection or projection as easily as JSON_TABLE().
The above is the detailed content of How to Query Strength Value of a \'Knight\' from a Nested JSON Array in MySQL?. For more information, please follow other related articles on the PHP Chinese website!