I am inserting my data in a database with json_encoded
. Now I want to search in "feature", but I can't.
MySQL query:
SELECT `id` , `attribs_json`
FROM `products`
WHERE `attribs_json` REGEXP '"1":{"value":[^"3"$]'
This query shows me all rows with key "1" and value is any thing not value is "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":""
}}
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
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)
Storing JSON in database violates the first normal form.
The best thing you can do is to normalize and store features in another table. Then you will be able to use a much better looking and performing query with joins. Your JSON even resembles the table.
Mysql 5.7 has builtin JSON functionality:
http://mysqlserverteam.com/mysql-5-7-lab-release-json-functions-part-2-querying-json-data/Correct pattern is:
WHERE `attribs_json` REGEXP '"1":{"value":[^}]*"3"[^}]*}'
[^}]
will match any character except}
I use this query
SELECT id FROM table_name WHERE field_name REGEXP '"key_name":"([^"])key_word([^"])"';
or
SELECT id FROM table_name WHERE field_name RLIKE '"key_name":"[[:<:]]key_word[[:>:]]"';
The first query I use it to search partial value. The second query I use it to search exact word.
for MySQL all (and 5.7)
SELECT LOWER(TRIM(BOTH 0x22 FROM TRIM(BOTH 0x20 FROM SUBSTRING(SUBSTRING(json_filed,LOCATE('\"ArrayItem\"',json_filed)+LENGTH('\"ArrayItem\"'),LOCATE(0x2C,SUBSTRING(json_filed,LOCATE('\"ArrayItem\"',json_filed)+LENGTH('\"ArrayItem\"')+1,LENGTH(json_filed)))),LOCATE(0x22,SUBSTRING(json_filed,LOCATE('\"ArrayItem\"',json_filed)+LENGTH('\"ArrayItem\"'),LOCATE(0x2C,SUBSTRING(json_filed,LOCATE('\"ArrayItem\"',json_filed)+LENGTH('\"ArrayItem\"')+1,LENGTH(json_filed))))),LENGTH(json_filed))))) AS result FROM `table`;
来源:https://stackoverflow.com/questions/30411210/how-to-search-json-data-in-mysql