skip to Main Content

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 

enter image description here

2

Answers


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

    SELECT JSON_EXTRACT(json_data, '$.key') AS key,
       JSON_EXTRACT(json_data, '$.value') AS value FROM my_table;
    

    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:

    {"person": {
    "name": "John",
    "age": 30}}
    

    You can retrieve the name and age values using the following query:

    SELECT JSON_EXTRACT(json_data, '$.person.name') AS name,
       JSON_EXTRACT(json_data, '$.person.age') AS age FROM my_table;
    

    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.

    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search