MySQL JSON: How to find object from key value

2020-04-18 08:20发布

问题:

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:

CREATE TABLE `fields` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `label` varchar(64) COLLATE utf8mb4_unicode_ci NOT NULL,
  `options` json DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

INSERT INTO `fields` (label, options) VALUES
(
  'My Field', 
  '[{"text": "Grass", "value": "1"}, {"text": "Synthetic (New Type - Soft)", "value": "2"}, {"text": "Synthetic  (Old Type - Hard)", "value": "3"}, {"text": "Gravel", "value": "5"}, {"text": "Clay", "value": "6"}, {"text": "Sand", "value": "7"}, {"text": "Grass/Synthetic Mix", "value": "8"}]'
);

DB Fiddle: https://www.db-fiddle.com/f/npPgVqh7fJL2JweGJ5LWXE/1

So what I would like is to select the string "Grass" from options by giving the ID 1.

But there doesn't seem to be a method to do that. I can get Grass by doing this:

select JSON_EXTRACT(`options`, '$[0].text') from `fields`;
// "Grass"

But that requires knowing the index from the array

I can partially get the index of the array like this:

select JSON_SEARCH(`options`, 'one', '1') from `fields`;
// "$[0].value"

And get the index itself through something really horrible like this:

select
REPLACE(REPLACE(JSON_SEARCH(`options`, 'one', '1'), '"$[', ''), '].value"', '')
from `fields`;
// 0

And even achieve what I want through something really horrible like this:

select
JSON_EXTRACT(`options`,CONCAT('$[',REPLACE(REPLACE(JSON_SEARCH(`options`, 'one', '1'), '"$[', ''), '].value"', ''), '].text'))
from `fields`;
// "Grass"

But there's got to be a better way right?

DB Fiddle: https://www.db-fiddle.com/f/npPgVqh7fJL2JweGJ5LWXE/1

回答1:

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.