MySQL JSON_SEARCH
JSON_SEARCH(doc, 'one', 'x') answers 'where in this document is the string x?' with a path such as "$.a".
- 카테고리
- Strings
- Returns
JSON (a path string or an array of paths), or NULL- In this category
- 170 of 172
구문
JSON_SEARCH(doc, 'one' | 'all', search_str [, escape_char [, path ...]])
엔진 지원
| 엔진 | Support | 메모 |
|---|---|---|
| SQL Server | Not built in | no direct function; recursive OPENJSON can rebuild paths |
| PostgreSQL | Different name or syntax | jsonb_path_exists with a filter tests for a value but returns no path |
| MySQL | 예 | JSON_SEARCH |
| SQLite | Different name or syntax | json_tree(doc) with WHERE atom = 'x' returns fullkey paths |
| Oracle | Different name or syntax | JSON_EXISTS with a filter tests for a value but returns no path |
예시
MySQL
SELECT JSON_SEARCH('{"a":"x","b":["y","x"]}', 'one', 'x') AS first_path,
JSON_SEARCH('{"a":"x","b":["y","x"]}', 'all', 'x') AS all_paths; -- "$.a", ["$.a", "$.b[1]"]
MySQL
SELECT JSON_REMOVE(doc, JSON_UNQUOTE(JSON_SEARCH(doc, 'one', 'old'))) AS cleaned FROM (SELECT '["new", "old"]' AS doc) AS t; -- ["new"]
SQLite
SELECT fullkey FROM json_tree('{"a":"x","b":["y","x"]}') WHERE atom = 'x'; -- $.a, $.b[1]
알아 두면 좋은 정보
- It finds string values only: JSON_SEARCH('[1,2]', 'one', '1') is NULL.
- The search string is a LIKE pattern, so % and _ are wildcards: 'ab%' matches both "abc" and "abd". Pass an escape character as the fourth argument to search for them literally.
- 'one' returns a single path as a JSON string and 'all' returns an array. Wrap the result in JSON_UNQUOTE before passing it to JSON_EXTRACT or JSON_REMOVE.
Questions about JSON_SEARCH
How do I remove an array element by value in MySQL?
Find its path and remove it: JSON_REMOVE(doc, JSON_UNQUOTE(JSON_SEARCH(doc, 'one', 'old'))). Guard against a NULL path when the value is absent, because JSON_REMOVE with a NULL path returns NULL.
Can JSON_SEARCH find numbers?
No. For numbers use JSON_CONTAINS(doc, '1') to test, or JSON_TABLE to unnest and filter.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
Cheat sheets for the engines that have it: PostgreSQL, MySQL, SQLite, Oracle.
Functions your engine actually has
SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.