mysql 查询 json 对象,MySQL JSON:如何从键值中找到对象

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"}]'

);

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?

解决方案

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值