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

标签 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"}

那么我如何才能从“misc”列中检索产品名称、图像路径和仅“group_id”值,如“40067”。

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

SELECT product_name,image_path,misc REGEXP '(.*\"group_id\":*)' as Misc FROM ref_products where product_id=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

这是一个 fiddle 来展示它的工作:http://sqlfiddle.com/#!2/ea02e/15

编辑 您可以通过在字符串中包含双引号和冒号来摆脱 +3 魔数(Magic Number),如下所示: substring_index(substr(misc,locate('"group_id":"',misc)+char_length('"group_id":"')),'"',1) as Misc

关于mysql - 如何在 MySQL 查询本身中检索存储在 JSON 数组中的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21594793/

相关文章:

Python - 将特定键的 json 数据转换为 csv 格式

json - 有没有办法让 jmeter 在响应数据选项卡中美化 json 数据?

php - 用户级逻辑

mysql - mysql查询真的很奇怪的错误

php - 将 Magento 的 var 目录放入 RAM

mysql - 没有找到适合 jdbc mysql 的驱动程序?

SQL Server 字符串执行带有输出参数的过程

java - SQL 选择查询错误

sql - 如何在SQL中使用Like多个值

mysql - 如何从 MySQL 中的 JSON 对象将键和值存储在表中