I Have one table i.e discount_details. I have 2 columns are the ID , DiscountTotal. I want to sum the each record line total json object with in the D array (64,10,10 are the 1st record values) . Like here 64,10,10 are the values,need to sum total value as 84 in the select query of MYSQL. I tried below examples but not working. Can please help on this issue.
SELECT JSON_EXTRACT(`DiscountTotal`, '$.D') AS total FROM tablename
2
Answers
To retrieve JSON object data in MySQL using a select query, you can make use of the JSON functions provided by MySQL. Here’s an example of how you can achieve this:
Let’s assume you have a table named my_table with a column named json_data that stores JSON objects. To retrieve data from the JSON object, you can use the JSON_EXTRACT function in your select query.
In the above query, json_data is the column containing the JSON object, and key and value are the keys within the JSON object that you want to extract. Adjust the path inside JSON_EXTRACT to match the structure of your JSON object.
If your JSON object is nested, you can use dot notation to traverse the object structure. For example, if your JSON object looks like this:
You can retrieve the name and age values using the following query:
Make sure to replace my_table with the actual name of your table, and adjust the column and path according to your JSON structure.
Note that the JSON functions are available starting from MySQL version 5.7.8. If you are using an older version, you may need to upgrade or consider alternative approaches like string manipulation to extract the desired values from the JSON object.
SELECT s.SNO, sum(t.Value)
FROM tablename s,
JSON_TABLE(
JSON_EXTRACT(
DiscountTotal
,’$[0].D’),"$[*]" COLUMNS(
Value INT PATH "$"
)
) t group by s.SNO