patternsqlMinor
Performing wildcard search using the json_contains function in mysql 5.7 and above
Viewed 0 times
performingthewildcardsearchabovefunctionmysqljson_containsusingand
Problem
I have some nested json data that i get using the
The problem with this approach is that I require the entire string "FirstName LastName" to find this row in the actual result.
Now I need to perform a wild card search. That is:-
should also return this entry to me in the final result. Can someone please suggest any workaround?
json_object() function. Now I need to to check whether a certain value exists for a particular key which I am using as follows in my query:-select json_object(..) from tblxyz
where json_contains(columnname, '{"MyName" : "FirstName LastName"}')The problem with this approach is that I require the entire string "FirstName LastName" to find this row in the actual result.
Now I need to perform a wild card search. That is:-
select json_object(..) from tblxyz
where json_contains(columnname, '{"MyName" : "FirstName"}')should also return this entry to me in the final result. Can someone please suggest any workaround?
Solution
You can use JSON_SEARCH with wildcards:
Will return the path:
If you want to filter by this, use an alias and check it in a
or.. in a
https://dev.mysql.com/doc/refman/5.7/en/json-search-functions.html
SET @j = '{"MyName": "FirstName LastName"}';
SELECT JSON_SEARCH(@j, 'all', 'FirstName%', NULL, '$.MyName');Will return the path:
"$.MyName"If you want to filter by this, use an alias and check it in a
HAVING clause:SELECT JSON_SEARCH(`json_col`, 'all', 'FirstName%', NULL, '$.MyName') as `search`
FROM `users`
HAVING `search` IS NOT NULL;or.. in a
WHERE:SELECT *
FROM `users`
WHERE JSON_SEARCH(`json_col`, 'all', 'FirstName%', NULL, '$.MyName') IS NOT NULL;https://dev.mysql.com/doc/refman/5.7/en/json-search-functions.html
Code Snippets
SET @j = '{"MyName": "FirstName LastName"}';
SELECT JSON_SEARCH(@j, 'all', 'FirstName%', NULL, '$.MyName');SELECT JSON_SEARCH(`json_col`, 'all', 'FirstName%', NULL, '$.MyName') as `search`
FROM `users`
HAVING `search` IS NOT NULL;SELECT *
FROM `users`
WHERE JSON_SEARCH(`json_col`, 'all', 'FirstName%', NULL, '$.MyName') IS NOT NULL;Context
StackExchange Database Administrators Q#222418, answer score: 6
Revisions (0)
No revisions yet.