MySQL Return JSON array index based on property value

后端 未结 2 1854
忘掉有多难
忘掉有多难 2020-12-22 00:41

I have a table with JSON data like this:

{\"a\": [{\"color\": \"blue\", \"value\": 15}, {\"color\": \"red\", \"value\": 30}]}

I need to get

相关标签:
2条回答
  • 2020-12-22 01:40

    Use JSON_SEARCH() to find the path to blue.

    SELECT JSON_EXTRACT(my_data, REPLACE(JSON_SEARCH(my_data, 'one', 'blue'), '.color', '.value'))
    

    JSON_SEARCH will return a string like $.a[0].color. REPLACE changes that to $.a[0].value, then you extract that element.

    0 讨论(0)
  • 2020-12-22 01:40

    Here's an example of using JSON_TABLE():

    select j.* from d, json_table(d.data, '$.a[*]' columns (
      color varchar(20) path '$.color', 
      value int path '$.value')
    ) as j;
    +-------+-------+
    | color | value |
    +-------+-------+
    | blue  |    15 |
    | red   |    30 |
    +-------+-------+
    

    You can then apply conditions in the WHERE clause, as if you had stored the data in a normal table.

    select j.* from d, json_table(d.data, '$.a[*]' columns (
      color varchar(20) path '$.color', 
      value int path '$.value')
    ) as j 
    where j.color = 'blue';
    +-------+-------+
    | color | value |
    +-------+-------+
    | blue  |    15 |
    +-------+-------+
    

    This requires you to write a complex query like this EVERY TIME you query the JSON data.

    One wonders if it would have been easier to store the JSON in a normal table from the start.

    I often recommend to MySQL users that storing data as JSON makes more work for you, if you need to make SQL expressions to reference individual fields within the JSON. I wouldn't use JSON in these cases, I'd explode the JSON array into rows, and the JSON fields into columns of a set of normal tables. Then you can write simpler queries, you can optimize with indexes, and you can use constraints and data types properly.

    JSON is the most easily misused feature of the recent MySQL releases.

    0 讨论(0)
提交回复
热议问题