MySQL JSON: How to find object from key value

前端 未结 1 1088
甜味超标
甜味超标 2021-01-22 01:43

I\'m trying to find a way to search a JSON object and get a particular key but search on another key.

Here is an example schema:



        
相关标签:
1条回答
  • 2021-01-22 02:11

    MySQL 8.0 provides JSON_TABLE() to help with cases like this.

    select field_options.* from fields, json_table(fields.options, 
    '$[*]' columns(
      text text path '$.text',
      value text path '$.value'
     )
    ) as field_options 
    where field_options.value = 1;
    +-------+-------+
    | text  | value |
    +-------+-------+
    | Grass | 1     |
    +-------+-------+
    

    But you have to do this complex JSON_TABLE() expression every time you want to write such a query.

    It would be simpler to not use JSON — instead, store data in a table with normal columns (one row per text/value pair). Then you can search for values you want in either column.

    SELECT * FROM field_options WHERE value = '1';
    

    99% of the uses of JSON in MySQL that I see on Stack Overflow would be solved easily by not using JSON.

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