简体   繁体   English

使用MySQL返回JSON字符串中的条目

[英]Return an entry within a JSON string with MySQL

I'm storing data as a JSON string in mysql because it comes with a lot of advantages in my situation. 我在mysql中将数据存储为JSON字符串,因为它在我的情况下具有很多优点。 These JSON strings can get quite large and within the JSON are other entries (with unique id's). 这些JSON字符串可以变得非常大,而JSON中的其他条目(具有唯一ID)。

At the moment I'm fetching the whole JSON string and then loop through it to find a particular entry by id. 目前我正在获取整个JSON字符串,然后遍历它以通过id查找特定条目。

Is there a way that I can fetch only the entry I'm looking for in the JSON string with MySQL only? 有没有办法只能在MySQL的JSON字符串中获取我正在寻找的条目? So that I don't have to fetch the whole JSON string and loop through it. 这样我就不必获取整个JSON字符串并循环遍历它。

use common_schema . 使用common_schema Here's an example: in the first i set variable that have a json format, assume this is your json in your record field table. 这是一个例子:在第一个具有json格式的i set变量中,假设这是你的记录字段表中的json。

SET @json = '{"id":"1","name":"number one"}';

and then parsing that variable (your field) into two separate columns with common_schema using extract_json_value() function: 然后使用extract_json_value()函数将该变量(您的字段)解析为使用common_schema的两个单独的列:

select common_schema.extract_json_value(@json,'/id') as ID,
    common_schema.extract_json_value(@json,'/name') as NAME

Ouput 输出继电器

+----------+-----------+
| ID       | NAME      |
+----------+-----------+
| 1        | number one|
+----------+-----------+

So you can implement in your table Query with CONDITIONS STATEMENT. 因此,您可以在表中使用CONDITIONS STATEMENT实现查询。 this example Query (JSON in field3): 此示例Query(field3中的JSON):

SELECT field1, field2, field3 as JSON,
       common_schema.extract_json_value(field3, '//sub1') as SUB1,
       common_schema.extract_json_value(field3, '//sub2') as SUB2
FROM your_table
WHERE common_schema.extract_json_value(field3, '//sub1') = 'YOUR_CONDITION'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM