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

时间:2014-02-06 05:30:18

标签: mysql sql json

我有下表

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”值类似“misc”列中的“40067”。

我尝试了以下查询,但它在Misc列中返回1/0。

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

任何想法的人怎么做?

3 个答案:

答案 0 :(得分:6)

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

答案 1 :(得分:3)

由于这个问题被问到MySQL已经引入了对JSON数据类型的支持。

在MySQL 5.7.8(及更高版本)中,您可以使用JSON_EXTRACT()或等效的->别名查询存储在列中的实际JSON字符串。

EG:

SELECT product_name, image_path, JSON_EXTRACT(misc,'$.group_id') AS `group_id` 
FROM ref_products 
WHERE product_id=1

请参阅:https://dev.mysql.com/doc/refman/5.7/en/json.html

答案 2 :(得分:2)

您可以使用MySQL的common_schema框架(与所有MySQL> = 5.1兼容),然后通过这种方式获得所需内容:

SELECT x.product_name, x.image_path, common_schema.extract_json_value(x.misc,'/group_id') as group_id FROM your_table x

common_schema框架:https://code.google.com/p/common-schema/