Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to search JSON data in MySQL?

I have inserted records in mysql DB, with json encoded data type, Now I have to make search within json encoded data, but i am not able to get proper data using following MySql query.

SELECT  `id` ,  `attribs_json`  FROM  `products`  WHERE  `attribs_json` REGEXP  '"1":{"value":[^"3"$]' 

Query results are key equal to "1" and value is anything except "3"

My data is:

{"feature":{"1":{"value":"["2","3"]"},             "2":{"value":["1"]},             "5":{"value":""},             "3":{"value":["1"]},             "9":{"value":""},             "4":{"value":"\u0633\u0627\u062a\u0646"},             "6":{"value":""},             "7":{"value":""},             "8":{"value":""}            }, "show_counter":"0", "show_counter_discount":"" }} 
like image 351
reza Avatar asked May 23 '15 09:05

reza


People also ask

How do I query JSON in MySQL?

Key takeaway for extracting data from a JSON field in MySQL: Use $. key to extract the value of a key from a JSON object. Use $[index] to extract the value of an element from a JSON array.

How does JSON value match MySQL?

MySQL supports the -> operator as shorthand for this function as used with 2 arguments where the left hand side is a JSON column identifier (not an expression) and the right hand side is the JSON path to be matched within the column.

How do I query JSON in SQL?

To query JSON data, you can use standard T-SQL. If you must create a query or report on JSON data, you can easily convert JSON data to rows and columns by calling the OPENJSON rowset function. For more information, see Convert JSON Data to Rows and Columns with OPENJSON (SQL Server).

How do I index a JSON column in MySQL?

In MySQL, the only way to index a JSON path expression is to add a virtual column that mirrors the path expression in question and build an index on the virtual column. As you can see, the title column is mapped to the $. title path expression on the properties JSON column.


2 Answers

If you have MySQL version >= 5.7, then you can try this:

SELECT JSON_EXTRACT(name, "$.id") AS name FROM table WHERE JSON_EXTRACT(name, "$.id") > 3 

Output:

+-------------------------------+ | name                          |  +-------------------------------+ | {"id": "4", "name": "Betty"}  |  +-------------------------------+ 


Please check MySQL reference manual for more details:
https://dev.mysql.com/doc/refman/5.7/en/json-search-functions.html

like image 114
Sachin Vairagi Avatar answered Oct 21 '22 07:10

Sachin Vairagi


If your are using MySQL Latest version following may help to reach your requirement.

select * from products where attribs_json->"$.feature.value[*]" in (1,3) 
like image 30
Vishnu Prasanth G Avatar answered Oct 21 '22 06:10

Vishnu Prasanth G