MySQL JSON: How to find object from key value

[*]

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

select field_options.* from fields cross join 
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.

Leave a Comment