小编典典

如何在MySQL查询本身中检索存储在JSON数组中的值?

sql

我有下表

product_id    product_name    image_path                             misc
----------   --------------  ------------                           ------
     1            flex        http://firstpl...      {"course_level_id":19,"group_id":"40067"}
     2           Android      http://firstpl...      {"course_level_id":20,"group_id":"40072"}

因此,如何从“杂项”列中检索product_name,image_path和仅“ group_id”值(如“ 40067”)。

我在下面的查询中尝试过,但在“杂项”列中返回1/0。

SELECT product_name,image_path,misc REGEXP '(.*\"group_id\":*)' as Misc FROM ref_products where product_id=1

有人知道该怎么做吗?


阅读 263

收藏
2021-03-08

共1个答案

小编典典

REGEXP函数仅返回0或1。您将不得不使用其他字符串函数。

试试这个:substr(misc,locate('group_id',misc)+11,5) as Misc。但这假设group_id始终具有5个字符。

因此,这是更好的:substring_index(substr(misc,locate('group_id',misc)+char_length('group_id')+3),'"',1) as Misc

这里是一个小提琴,以显示它的工作原理:http :
//sqlfiddle.com/#!2/ea02e/15

编辑 您可以+3通过在字符串中包含双引号和冒号来消除幻数:
substring_index(substr(misc,locate('"group_id":"',misc)+char_length('"group_id":"')),'"',1) as Misc

2021-03-08