Rechercher dans le manuel MySQL

12.17.3 Functions That Search JSON Values

The functions in this section perform search or comparison operations on JSON values to extract data from them, report whether data exists at a location within them, or report the path to data within them. The MEMBER OF() operator is also documented herein.

  • JSON_CONTAINS(target, candidate[, path])

    Indicates by returning 1 or 0 whether a given candidate JSON document is contained within a target JSON document, or—if a path argument was supplied—whether the candidate is found at a specific path within the target. Returns NULL if any argument is NULL, or if the path argument does not identify a section of the target document. An error occurs if target or candidate is not a valid JSON document, or if the path argument is not a valid path expression or contains a * or ** wildcard.

    To check only whether any data exists at the path, use JSON_CONTAINS_PATH() instead.

    The following rules define containment:

    • A candidate scalar is contained in a target scalar if and only if they are comparable and are equal. Two scalar values are comparable if they have the same JSON_TYPE() types, with the exception that values of types INTEGER and DECIMAL are also comparable to each other.

    • A candidate array is contained in a target array if and only if every element in the candidate is contained in some element of the target.

    • A candidate nonarray is contained in a target array if and only if the candidate is contained in some element of the target.

    • A candidate object is contained in a target object if and only if for each key in the candidate there is a key with the same name in the target and the value associated with the candidate key is contained in the value associated with the target key.

    Otherwise, the candidate value is not contained in the target document.

    Starting with MySQL 8.0.17, queries using JSON_CONTAINS() on InnoDB tables can be optimized using multi-valued indexes; see Multi-Valued Indexes, for more information.

    1. mysql> SET @j = '{"a": 1, "b": 2, "c": {"d": 4}}';
    2. mysql> SET @j2 = '1';
    3. mysql> SELECT JSON_CONTAINS(@j, @j2, '$.a');
    4. +-------------------------------+
    5. | JSON_CONTAINS(@j, @j2, '$.a') |
    6. +-------------------------------+
    7. |                             1 |
    8. +-------------------------------+
    9. mysql> SELECT JSON_CONTAINS(@j, @j2, '$.b');
    10. +-------------------------------+
    11. | JSON_CONTAINS(@j, @j2, '$.b') |
    12. +-------------------------------+
    13. |                             0 |
    14. +-------------------------------+
    15.  
    16. mysql> SET @j2 = '{"d": 4}';
    17. mysql> SELECT JSON_CONTAINS(@j, @j2, '$.a');
    18. +-------------------------------+
    19. | JSON_CONTAINS(@j, @j2, '$.a') |
    20. +-------------------------------+
    21. |                             0 |
    22. +-------------------------------+
    23. mysql> SELECT JSON_CONTAINS(@j, @j2, '$.c');
    24. +-------------------------------+
    25. | JSON_CONTAINS(@j, @j2, '$.c') |
    26. +-------------------------------+
    27. |                             1 |
    28. +-------------------------------+
  • JSON_CONTAINS_PATH(json_doc, one_or_all, path[, path] ...)

    Returns 0 or 1 to indicate whether a JSON document contains data at a given path or paths. Returns NULL if any argument is NULL. An error occurs if the json_doc argument is not a valid JSON document, any path argument is not a valid path expression, or one_or_all is not 'one' or 'all'.

    To check for a specific value at a path, use JSON_CONTAINS() instead.

    The return value is 0 if no specified path exists within the document. Otherwise, the return value depends on the one_or_all argument:

    • 'one': 1 if at least one path exists within the document, 0 otherwise.

    • 'all': 1 if all paths exist within the document, 0 otherwise.

    1. mysql> SET @j = '{"a": 1, "b": 2, "c": {"d": 4}}';
    2. mysql> SELECT JSON_CONTAINS_PATH(@j, 'one', '$.a', '$.e');
    3. +---------------------------------------------+
    4. | JSON_CONTAINS_PATH(@j, 'one', '$.a', '$.e') |
    5. +---------------------------------------------+
    6. |                                           1 |
    7. +---------------------------------------------+
    8. mysql> SELECT JSON_CONTAINS_PATH(@j, 'all', '$.a', '$.e');
    9. +---------------------------------------------+
    10. | JSON_CONTAINS_PATH(@j, 'all', '$.a', '$.e') |
    11. +---------------------------------------------+
    12. |                                           0 |
    13. +---------------------------------------------+
    14. mysql> SELECT JSON_CONTAINS_PATH(@j, 'one', '$.c.d');
    15. +----------------------------------------+
    16. | JSON_CONTAINS_PATH(@j, 'one', '$.c.d') |
    17. +----------------------------------------+
    18. |                                      1 |
    19. +----------------------------------------+
    20. mysql> SELECT JSON_CONTAINS_PATH(@j, 'one', '$.a.d');
    21. +----------------------------------------+
    22. | JSON_CONTAINS_PATH(@j, 'one', '$.a.d') |
    23. +----------------------------------------+
    24. |                                      0 |
    25. +----------------------------------------+
  • JSON_EXTRACT(json_doc, path[, path] ...)

    Returns data from a JSON document, selected from the parts of the document matched by the path arguments. Returns NULL if any argument is NULL or no paths locate a value in the document. An error occurs if the json_doc argument is not a valid JSON document or any path argument is not a valid path expression.

    The return value consists of all values matched by the path arguments. If it is possible that those arguments could return multiple values, the matched values are autowrapped as an array, in the order corresponding to the paths that produced them. Otherwise, the return value is the single matched value.

    1. mysql> SELECT JSON_EXTRACT('[10, 20, [30, 40]]', '$[1]');
    2. +--------------------------------------------+
    3. | JSON_EXTRACT('[10, 20, [30, 40]]', '$[1]') |
    4. +--------------------------------------------+
    5. | 20                                         |
    6. +--------------------------------------------+
    7. mysql> SELECT JSON_EXTRACT('[10, 20, [30, 40]]', '$[1]', '$[0]');
    8. +----------------------------------------------------+
    9. | JSON_EXTRACT('[10, 20, [30, 40]]', '$[1]', '$[0]') |
    10. +----------------------------------------------------+
    11. | [20, 10]                                           |
    12. +----------------------------------------------------+
    13. mysql> SELECT JSON_EXTRACT('[10, 20, [30, 40]]', '$[2][*]');
    14. +-----------------------------------------------+
    15. | JSON_EXTRACT('[10, 20, [30, 40]]', '$[2][*]') |
    16. +-----------------------------------------------+
    17. | [30, 40]                                      |
    18. +-----------------------------------------------+

    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.

  • column->path

    The -> operator serves as an alias for the JSON_EXTRACT() function when used with two arguments, a column identifier on the left and a JSON path on the right that is evaluated against the JSON document (the column value). You can use such expressions in place of column identifiers wherever they occur in SQL statements.

    The two SELECT statements shown here produce the same output:

    1. mysql> SELECT c, JSON_EXTRACT(c, "$.id"), g
    2.      > FROM jemp
    3.      > WHERE JSON_EXTRACT(c, "$.id") > 1
    4.      > ORDER BY JSON_EXTRACT(c, "$.name");
    5. +-------------------------------+-----------+------+
    6. | c                             | c->"$.id" | g    |
    7. +-------------------------------+-----------+------+
    8. | {"id": "3", "name": "Barney"} | "3"       |    3 |
    9. | {"id": "4", "name": "Betty"}  | "4"       |    4 |
    10. | {"id": "2", "name": "Wilma"}  | "2"       |    2 |
    11. +-------------------------------+-----------+------+
    12. 3 rows in set (0.00 sec)
    13.  
    14. mysql> SELECT c, c->"$.id", g
    15.      > FROM jemp
    16.      > WHERE c->"$.id" > 1
    17.      > ORDER BY c->"$.name";
    18. +-------------------------------+-----------+------+
    19. | c                             | c->"$.id" | g    |
    20. +-------------------------------+-----------+------+
    21. | {"id": "3", "name": "Barney"} | "3"       |    3 |
    22. | {"id": "4", "name": "Betty"}  | "4"       |    4 |
    23. | {"id": "2", "name": "Wilma"}  | "2"       |    2 |
    24. +-------------------------------+-----------+------+
    25. 3 rows in set (0.00 sec)

    This functionality is not limited to SELECT, as shown here:

    1. mysql> ALTER TABLE jemp ADD COLUMN n INT;
    2. Query OK, 0 rows affected (0.68 sec)
    3. Records: 0  Duplicates: 0  Warnings: 0
    4.  
    5. mysql> UPDATE jemp SET n=1 WHERE c->"$.id" = "4";
    6. Query OK, 1 row affected (0.04 sec)
    7. Rows matched: 1  Changed: 1  Warnings: 0
    8.  
    9. mysql> SELECT c, c->"$.id", g, n
    10.      > FROM jemp
    11.      > WHERE JSON_EXTRACT(c, "$.id") > 1
    12.      > ORDER BY c->"$.name";
    13. +-------------------------------+-----------+------+------+
    14. | c                             | c->"$.id" | g    | n    |
    15. +-------------------------------+-----------+------+------+
    16. | {"id": "3", "name": "Barney"} | "3"       |    3 | NULL |
    17. | {"id": "4", "name": "Betty"}  | "4"       |    4 |    1 |
    18. | {"id": "2", "name": "Wilma"}  | "2"       |    2 | NULL |
    19. +-------------------------------+-----------+------+------+
    20. 3 rows in set (0.00 sec)
    21.  
    22. mysql> DELETE FROM jemp WHERE c->"$.id" = "4";
    23. Query OK, 1 row affected (0.04 sec)
    24.  
    25. mysql> SELECT c, c->"$.id", g, n
    26.      > FROM jemp
    27.      > WHERE JSON_EXTRACT(c, "$.id") > 1
    28.      > ORDER BY c->"$.name";
    29. +-------------------------------+-----------+------+------+
    30. | c                             | c->"$.id" | g    | n    |
    31. +-------------------------------+-----------+------+------+
    32. | {"id": "3", "name": "Barney"} | "3"       |    3 | NULL |
    33. | {"id": "2", "name": "Wilma"}  | "2"       |    2 | NULL |
    34. +-------------------------------+-----------+------+------+
    35. 2 rows in set (0.00 sec)

    (See Indexing a Generated Column to Provide a JSON Column Index, for the statements used to create and populate the table just shown.)

    This also works with JSON array values, as shown here:

    1. mysql> CREATE TABLE tj10 (a JSON, b INT);
    2. Query OK, 0 rows affected (0.26 sec)
    3.  
    4. mysql> INSERT INTO tj10
    5.      > VALUES ("[3,10,5,17,44]", 33), ("[3,10,5,17,[22,44,66]]", 0);
    6. Query OK, 1 row affected (0.04 sec)
    7.  
    8. mysql> SELECT a->"$[4]" FROM tj10;
    9. +--------------+
    10. | a->"$[4]"    |
    11. +--------------+
    12. | 44           |
    13. | [22, 44, 66] |
    14. +--------------+
    15. 2 rows in set (0.00 sec)
    16.  
    17. mysql> SELECT * FROM tj10 WHERE a->"$[0]" = 3;
    18. +------------------------------+------+
    19. | a                            | b    |
    20. +------------------------------+------+
    21. | [3, 10, 5, 17, 44]           |   33 |
    22. | [3, 10, 5, 17, [22, 44, 66]] |    0 |
    23. +------------------------------+------+
    24. 2 rows in set (0.00 sec)

    Nested arrays are supported. An expression using -> evaluates as NULL if no matching key is found in the target JSON document, as shown here:

    1. mysql> SELECT * FROM tj10 WHERE a->"$[4][1]" IS NOT NULL;
    2. +------------------------------+------+
    3. | a                            | b    |
    4. +------------------------------+------+
    5. | [3, 10, 5, 17, [22, 44, 66]] |    0 |
    6. +------------------------------+------+
    7.  
    8. mysql> SELECT a->"$[4][1]" FROM tj10;
    9. +--------------+
    10. | a->"$[4][1]" |
    11. +--------------+
    12. | NULL         |
    13. | 44           |
    14. +--------------+
    15. 2 rows in set (0.00 sec)

    This is the same behavior as seen in such cases when using JSON_EXTRACT():

    1. mysql> SELECT JSON_EXTRACT(a, "$[4][1]") FROM tj10;
    2. +----------------------------+
    3. | JSON_EXTRACT(a, "$[4][1]") |
    4. +----------------------------+
    5. | NULL                       |
    6. | 44                         |
    7. +----------------------------+
    8. 2 rows in set (0.00 sec)
  • column->>path

    This is an improved, unquoting extraction operator. Whereas the -> operator simply extracts a value, the ->> operator in addition unquotes the extracted result. In other words, given a JSON column value column and a path expression path, the following three expressions return the same value:

    The ->> operator can be used wherever JSON_UNQUOTE(JSON_EXTRACT()) would be allowed. This includes (but is not limited to) SELECT lists, WHERE and HAVING clauses, and ORDER BY and GROUP BY clauses.

    The next few statements demonstrate some ->> operator equivalences with other expressions in the mysql client:

    1. mysql> SELECT * FROM jemp WHERE g > 2;
    2. +-------------------------------+------+
    3. | c                             | g    |
    4. +-------------------------------+------+
    5. | {"id": "3", "name": "Barney"} |    3 |
    6. | {"id": "4", "name": "Betty"}  |    4 |
    7. +-------------------------------+------+
    8. 2 rows in set (0.01 sec)
    9.  
    10. mysql> SELECT c->'$.name' AS name
    11.     ->     FROM jemp WHERE g > 2;
    12. +----------+
    13. | name     |
    14. +----------+
    15. | "Barney" |
    16. | "Betty"  |
    17. +----------+
    18. 2 rows in set (0.00 sec)
    19.  
    20. mysql> SELECT JSON_UNQUOTE(c->'$.name') AS name
    21.     ->     FROM jemp WHERE g > 2;
    22. +--------+
    23. | name   |
    24. +--------+
    25. | Barney |
    26. | Betty  |
    27. +--------+
    28. 2 rows in set (0.00 sec)
    29.  
    30. mysql> SELECT c->>'$.name' AS name
    31.     ->     FROM jemp WHERE g > 2;
    32. +--------+
    33. | name   |
    34. +--------+
    35. | Barney |
    36. | Betty  |
    37. +--------+
    38. 2 rows in set (0.00 sec)

    See Indexing a Generated Column to Provide a JSON Column Index, for the SQL statements used to create and populate the jemp table in the set of examples just shown.

    This operator can also be used with JSON arrays, as shown here:

    1. mysql> CREATE TABLE tj10 (a JSON, b INT);
    2. Query OK, 0 rows affected (0.26 sec)
    3.  
    4. mysql> INSERT INTO tj10 VALUES
    5.     ->     ('[3,10,5,"x",44]', 33),
    6.     ->     ('[3,10,5,17,[22,"y",66]]', 0);
    7. Query OK, 2 rows affected (0.04 sec)
    8. Records: 2  Duplicates: 0  Warnings: 0
    9.  
    10. mysql> SELECT a->"$[3]", a->"$[4][1]" FROM tj10;
    11. +-----------+--------------+
    12. | a->"$[3]" | a->"$[4][1]" |
    13. +-----------+--------------+
    14. | "x"       | NULL         |
    15. | 17        | "y"          |
    16. +-----------+--------------+
    17. 2 rows in set (0.00 sec)
    18.  
    19. mysql> SELECT a->>"$[3]", a->>"$[4][1]" FROM tj10;
    20. +------------+---------------+
    21. | a->>"$[3]" | a->>"$[4][1]" |
    22. +------------+---------------+
    23. | x          | NULL          |
    24. | 17         | y             |
    25. +------------+---------------+
    26. 2 rows in set (0.00 sec)

    As with ->, the ->> operator is always expanded in the output of EXPLAIN, as the following example demonstrates:

    1. mysql> EXPLAIN SELECT c->>'$.name' AS name
    2.     ->     FROM jemp WHERE g > 2\G
    3. *************************** 1. row ***************************
    4.            id: 1
    5.   select_type: SIMPLE
    6.         table: jemp
    7.    partitions: NULL
    8.          type: range
    9. possible_keys: i
    10.           key: i
    11.       key_len: 5
    12.           ref: NULL
    13.          rows: 2
    14.      filtered: 100.00
    15.         Extra: Using where
    16. 1 row in set, 1 warning (0.00 sec)
    17.  
    18. mysql> SHOW WARNINGS\G
    19. *************************** 1. row ***************************
    20.   Level: Note
    21.    Code: 1003
    22. Message: /* select#1 */ select
    23. json_unquote(json_extract(`jtest`.`jemp`.`c`,'$.name')) AS `name` from
    24. `jtest`.`jemp` where (`jtest`.`jemp`.`g` > 2)
    25. 1 row in set (0.00 sec)

    This is similar to how MySQL expands the -> operator in the same circumstances.

  • JSON_KEYS(json_doc[, path])

    Returns the keys from the top-level value of a JSON object as a JSON array, or, if a path argument is given, the top-level keys from the selected path. Returns NULL if any argument is NULL, the json_doc argument is not an object, or path, if given, does not locate an object. An error occurs if the json_doc argument is not a valid JSON document or the path argument is not a valid path expression or contains a * or ** wildcard.

    The result array is empty if the selected object is empty. If the top-level value has nested subobjects, the return value does not include keys from those subobjects.

    1. mysql> SELECT JSON_KEYS('{"a": 1, "b": {"c": 30}}');
    2. +---------------------------------------+
    3. | JSON_KEYS('{"a": 1, "b": {"c": 30}}') |
    4. +---------------------------------------+
    5. | ["a", "b"]                            |
    6. +---------------------------------------+
    7. mysql> SELECT JSON_KEYS('{"a": 1, "b": {"c": 30}}', '$.b');
    8. +----------------------------------------------+
    9. | JSON_KEYS('{"a": 1, "b": {"c": 30}}', '$.b') |
    10. +----------------------------------------------+
    11. | ["c"]                                        |
    12. +----------------------------------------------+
  • JSON_OVERLAPS(json_doc1, json_doc2)

    Compares two JSON documents. Returns true (1) if the two document have any key-value pairs or array elements in common. If both arguments are scalars, the function performs a simple equality test.

    This function serves as counterpart to JSON_CONTAINS(), which requires all elements of the array searched for to be present in the array searched in. Thus, JSON_CONTAINS() performs an AND operation on search keys, while JSON_OVERLAPS() performs an OR operation.

    Queries on JSON columns of InnoDB tables using JSON_OVERLAPS() in the WHERE clause can be optimized using multi-valued indexes. Multi-Valued Indexes, provides detailed information and examples.

    When two comparing two arrays, JSON_OVERLAPS() returns true if they share one or more array elements in common, and false if they do not:

    1. mysql> SELECT JSON_OVERLAPS("[1,3,5,7]", "[2,5,7]");
    2. +---------------------------------------+
    3. | JSON_OVERLAPS("[1,3,5,7]", "[2,5,7]") |
    4. +---------------------------------------+
    5. |                                     1 |
    6. +---------------------------------------+
    7. 1 row in set (0.00 sec)
    8.  
    9. mysql> SELECT JSON_OVERLAPS("[1,3,5,7]", "[2,6,7]");
    10. +---------------------------------------+
    11. | JSON_OVERLAPS("[1,3,5,7]", "[2,6,7]") |
    12. +---------------------------------------+
    13. |                                     1 |
    14. +---------------------------------------+
    15. 1 row in set (0.00 sec)
    16.  
    17. mysql> SELECT JSON_OVERLAPS("[1,3,5,7]", "[2,6,8]");
    18. +---------------------------------------+
    19. | JSON_OVERLAPS("[1,3,5,7]", "[2,6,8]") |
    20. +---------------------------------------+
    21. |                                     0 |
    22. +---------------------------------------+
    23. 1 row in set (0.00 sec)

    Partial matches are treated as no match, as shown here:

    1. mysql> SELECT JSON_OVERLAPS('[[1,2],[3,4],5]', '[1,[2,3],[4,5]]');
    2. +-----------------------------------------------------+
    3. | JSON_OVERLAPS('[[1,2],[3,4],5]', '[1,[2,3],[4,5]]') |
    4. +-----------------------------------------------------+
    5. |                                                   0 |
    6. +-----------------------------------------------------+
    7. 1 row in set (0.00 sec)

    When comparing objects, the result is true if they have at least one key-value pair in common.

    1. mysql> SELECT JSON_OVERLAPS('{"a":1,"b":10,"d":10}', '{"c":1,"e":10,"f":1,"d":10}');
    2. +-----------------------------------------------------------------------+
    3. | JSON_OVERLAPS('{"a":1,"b":10,"d":10}', '{"c":1,"e":10,"f":1,"d":10}') |
    4. +-----------------------------------------------------------------------+
    5. |                                                                     1 |
    6. +-----------------------------------------------------------------------+
    7. 1 row in set (0.00 sec)
    8.  
    9. mysql> SELECT JSON_OVERLAPS('{"a":1,"b":10,"d":10}', '{"a":5,"e":10,"f":1,"d":20}');
    10. +-----------------------------------------------------------------------+
    11. | JSON_OVERLAPS('{"a":1,"b":10,"d":10}', '{"a":5,"e":10,"f":1,"d":20}') |
    12. +-----------------------------------------------------------------------+
    13. |                                                                     0 |
    14. +-----------------------------------------------------------------------+
    15. 1 row in set (0.00 sec)

    If two scalars are used as the arguments to the function, JSON_OVERLAPS() performs a simple test for equality:

    1. mysql> SELECT JSON_OVERLAPS('5', '5');
    2. +-------------------------+
    3. | JSON_OVERLAPS('5', '5') |
    4. +-------------------------+
    5. |                       1 |
    6. +-------------------------+
    7. 1 row in set (0.00 sec)
    8.  
    9. mysql> SELECT JSON_OVERLAPS('5', '6');
    10. +-------------------------+
    11. | JSON_OVERLAPS('5', '6') |
    12. +-------------------------+
    13. |                       0 |
    14. +-------------------------+
    15. 1 row in set (0.00 sec)

    When comparing a scalar with an array, JSON_OVERLAPS() attempts to treat the scalar as an array element. In this example, the second argument 6 is interpreted as [6], as shown here:

    1. mysql> SELECT JSON_OVERLAPS('[4,5,6,7]', '6');
    2. +---------------------------------+
    3. | JSON_OVERLAPS('[4,5,6,7]', '6') |
    4. +---------------------------------+
    5. |                               1 |
    6. +---------------------------------+
    7. 1 row in set (0.00 sec)

    The function does not perform type conversions:

    1. mysql> SELECT JSON_OVERLAPS('[4,5,"6",7]', '6');
    2. +-----------------------------------+
    3. | JSON_OVERLAPS('[4,5,"6",7]', '6') |
    4. +-----------------------------------+
    5. |                                 0 |
    6. +-----------------------------------+
    7. 1 row in set (0.00 sec)
    8.  
    9. mysql> SELECT JSON_OVERLAPS('[4,5,6,7]', '"6"');
    10. +-----------------------------------+
    11. | JSON_OVERLAPS('[4,5,6,7]', '"6"') |
    12. +-----------------------------------+
    13. |                                 0 |
    14. +-----------------------------------+
    15. 1 row in set (0.00 sec)

    JSON_OVERLAPS() was added in MySQL 8.0.17.

  • JSON_SEARCH(json_doc, one_or_all, search_str[, escape_char[, path] ...])

    Returns the path to the given string within a JSON document. Returns NULL if any of the json_doc, search_str, or path arguments are NULL; no path exists within the document; or search_str is not found. An error occurs if the json_doc argument is not a valid JSON document, any path argument is not a valid path expression, one_or_all is not 'one' or 'all', or escape_char is not a constant expression.

    The one_or_all argument affects the search as follows:

    • 'one': The search terminates after the first match and returns one path string. It is undefined which match is considered first.

    • 'all': The search returns all matching path strings such that no duplicate paths are included. If there are multiple strings, they are autowrapped as an array. The order of the array elements is undefined.

    Within the search_str search string argument, the % and _ characters work as for the LIKE operator: % matches any number of characters (including zero characters), and _ matches exactly one character.

    To specify a literal % or _ character in the search string, precede it by the escape character. The default is \ if the escape_char argument is missing or NULL. Otherwise, escape_char must be a constant that is empty or one character.

    For more information about matching and escape character behavior, see the description of LIKE in Section 12.5.1, “String Comparison Functions and Operators”. For escape character handling, a difference from the LIKE behavior is that the escape character for JSON_SEARCH() must evaluate to a constant at compile time, not just at execution time. For example, if JSON_SEARCH() is used in a prepared statement and the escape_char argument is supplied using a ? parameter, the parameter value might be constant at execution time, but is not at compile time.

    1. mysql> SET @j = '["abc", [{"k": "10"}, "def"], {"x":"abc"}, {"y":"bcd"}]';
    2.  
    3. mysql> SELECT JSON_SEARCH(@j, 'one', 'abc');
    4. +-------------------------------+
    5. | JSON_SEARCH(@j, 'one', 'abc') |
    6. +-------------------------------+
    7. | "$[0]"                        |
    8. +-------------------------------+
    9.  
    10. mysql> SELECT JSON_SEARCH(@j, 'all', 'abc');
    11. +-------------------------------+
    12. | JSON_SEARCH(@j, 'all', 'abc') |
    13. +-------------------------------+
    14. | ["$[0]", "$[2].x"]            |
    15. +-------------------------------+
    16.  
    17. mysql> SELECT JSON_SEARCH(@j, 'all', 'ghi');
    18. +-------------------------------+
    19. | JSON_SEARCH(@j, 'all', 'ghi') |
    20. +-------------------------------+
    21. | NULL                          |
    22. +-------------------------------+
    23.  
    24. mysql> SELECT JSON_SEARCH(@j, 'all', '10');
    25. +------------------------------+
    26. | JSON_SEARCH(@j, 'all', '10') |
    27. +------------------------------+
    28. | "$[1][0].k"                  |
    29. +------------------------------+
    30.  
    31. mysql> SELECT JSON_SEARCH(@j, 'all', '10', NULL, '$');
    32. +-----------------------------------------+
    33. | JSON_SEARCH(@j, 'all', '10', NULL, '$') |
    34. +-----------------------------------------+
    35. | "$[1][0].k"                             |
    36. +-----------------------------------------+
    37.  
    38. mysql> SELECT JSON_SEARCH(@j, 'all', '10', NULL, '$[*]');
    39. +--------------------------------------------+
    40. | JSON_SEARCH(@j, 'all', '10', NULL, '$[*]') |
    41. +--------------------------------------------+
    42. | "$[1][0].k"                                |
    43. +--------------------------------------------+
    44.  
    45. mysql> SELECT JSON_SEARCH(@j, 'all', '10', NULL, '$**.k');
    46. +---------------------------------------------+
    47. | JSON_SEARCH(@j, 'all', '10', NULL, '$**.k') |
    48. +---------------------------------------------+
    49. | "$[1][0].k"                                 |
    50. +---------------------------------------------+
    51.  
    52. mysql> SELECT JSON_SEARCH(@j, 'all', '10', NULL, '$[*][0].k');
    53. +-------------------------------------------------+
    54. | JSON_SEARCH(@j, 'all', '10', NULL, '$[*][0].k') |
    55. +-------------------------------------------------+
    56. | "$[1][0].k"                                     |
    57. +-------------------------------------------------+
    58.  
    59. mysql> SELECT JSON_SEARCH(@j, 'all', '10', NULL, '$[1]');
    60. +--------------------------------------------+
    61. | JSON_SEARCH(@j, 'all', '10', NULL, '$[1]') |
    62. +--------------------------------------------+
    63. | "$[1][0].k"                                |
    64. +--------------------------------------------+
    65.  
    66. mysql> SELECT JSON_SEARCH(@j, 'all', '10', NULL, '$[1][0]');
    67. +-----------------------------------------------+
    68. | JSON_SEARCH(@j, 'all', '10', NULL, '$[1][0]') |
    69. +-----------------------------------------------+
    70. | "$[1][0].k"                                   |
    71. +-----------------------------------------------+
    72.  
    73. mysql> SELECT JSON_SEARCH(@j, 'all', 'abc', NULL, '$[2]');
    74. +---------------------------------------------+
    75. | JSON_SEARCH(@j, 'all', 'abc', NULL, '$[2]') |
    76. +---------------------------------------------+
    77. | "$[2].x"                                    |
    78. +---------------------------------------------+
    79.  
    80. mysql> SELECT JSON_SEARCH(@j, 'all', '%a%');
    81. +-------------------------------+
    82. | JSON_SEARCH(@j, 'all', '%a%') |
    83. +-------------------------------+
    84. | ["$[0]", "$[2].x"]            |
    85. +-------------------------------+
    86.  
    87. mysql> SELECT JSON_SEARCH(@j, 'all', '%b%');
    88. +-------------------------------+
    89. | JSON_SEARCH(@j, 'all', '%b%') |
    90. +-------------------------------+
    91. | ["$[0]", "$[2].x", "$[3].y"]  |
    92. +-------------------------------+
    93.  
    94. mysql> SELECT JSON_SEARCH(@j, 'all', '%b%', NULL, '$[0]');
    95. +---------------------------------------------+
    96. | JSON_SEARCH(@j, 'all', '%b%', NULL, '$[0]') |
    97. +---------------------------------------------+
    98. | "$[0]"                                      |
    99. +---------------------------------------------+
    100.  
    101. mysql> SELECT JSON_SEARCH(@j, 'all', '%b%', NULL, '$[2]');
    102. +---------------------------------------------+
    103. | JSON_SEARCH(@j, 'all', '%b%', NULL, '$[2]') |
    104. +---------------------------------------------+
    105. | "$[2].x"                                    |
    106. +---------------------------------------------+
    107.  
    108. mysql> SELECT JSON_SEARCH(@j, 'all', '%b%', NULL, '$[1]');
    109. +---------------------------------------------+
    110. | JSON_SEARCH(@j, 'all', '%b%', NULL, '$[1]') |
    111. +---------------------------------------------+
    112. | NULL                                        |
    113. +---------------------------------------------+
    114.  
    115. mysql> SELECT JSON_SEARCH(@j, 'all', '%b%', '', '$[1]');
    116. +-------------------------------------------+
    117. | JSON_SEARCH(@j, 'all', '%b%', '', '$[1]') |
    118. +-------------------------------------------+
    119. | NULL                                      |
    120. +-------------------------------------------+
    121.  
    122. mysql> SELECT JSON_SEARCH(@j, 'all', '%b%', '', '$[3]');
    123. +-------------------------------------------+
    124. | JSON_SEARCH(@j, 'all', '%b%', '', '$[3]') |
    125. +-------------------------------------------+
    126. | "$[3].y"                                  |
    127. +-------------------------------------------+

    For more information about the JSON path syntax supported by MySQL, including rules governing the wildcard operators * and **, see JSON Path Syntax.

  • value MEMBER OF(json_array)

    Returns true (1) if value is an element of json_array, otherwise returns false (0). value must be a scalar or a JSON document; if it is a scalar, the operator attempts to treat it as an element of a JSON array.

    Queries using MEMBER OF() on JSON columns of InnoDB tables in the WHERE clause can be optimized using multi-valued indexes. See Multi-Valued Indexes, for detailed information and examples.

    Simple scalars are treated as array values, as shown here:

    1. mysql> SELECT 17 MEMBER OF('[23, "abc", 17, "ab", 10]');
    2. +-------------------------------------------+
    3. | 17 MEMBER OF('[23, "abc", 17, "ab", 10]') |
    4. +-------------------------------------------+
    5. |                                         1 |
    6. +-------------------------------------------+
    7. 1 row in set (0.00 sec)
    8.  
    9. mysql> SELECT 'ab' MEMBER OF('[23, "abc", 17, "ab", 10]');
    10. +---------------------------------------------+
    11. | 'ab' MEMBER OF('[23, "abc", 17, "ab", 10]') |
    12. +---------------------------------------------+
    13. |                                           1 |
    14. +---------------------------------------------+
    15. 1 row in set (0.00 sec)

    Partial matches of array element values do not match:

    1. mysql> SELECT 7 MEMBER OF('[23, "abc", 17, "ab", 10]');
    2. +------------------------------------------+
    3. | 7 MEMBER OF('[23, "abc", 17, "ab", 10]') |
    4. +------------------------------------------+
    5. |                                        0 |
    6. +------------------------------------------+
    7. 1 row in set (0.00 sec)
    1. mysql> SELECT 'a' MEMBER OF('[23, "abc", 17, "ab", 10]');
    2. +--------------------------------------------+
    3. | 'a' MEMBER OF('[23, "abc", 17, "ab", 10]') |
    4. +--------------------------------------------+
    5. |                                          0 |
    6. +--------------------------------------------+
    7. 1 row in set (0.00 sec)

    Conversions to and from string types are not performed:

    1. mysql> SELECT
    2.     -> 17 MEMBER OF('[23, "abc", "17", "ab", 10]'),
    3.     -> "17" MEMBER OF('[23, "abc", 17, "ab", 10]')\G
    4. *************************** 1. row ***************************
    5. 17 MEMBER OF('[23, "abc", "17", "ab", 10]'): 0
    6. "17" MEMBER OF('[23, "abc", 17, "ab", 10]'): 0
    7. 1 row in set (0.00 sec)

    To use this operator with a value which itself an array, it is necessary to cast it explicitly as a JSON array. You can do this with CAST(... AS JSON):

    1. mysql> SELECT CAST('[4,5]' AS JSON) MEMBER OF('[[3,4],[4,5]]');
    2. +--------------------------------------------------+
    3. | CAST('[4,5]' AS JSON) MEMBER OF('[[3,4],[4,5]]') |
    4. +--------------------------------------------------+
    5. |                                                1 |
    6. +--------------------------------------------------+
    7. 1 row in set (0.00 sec)

    It is also possible to perform the necessary cast using the JSON_ARRAY() function, like this:

    1. mysql> SELECT JSON_ARRAY(4,5) MEMBER OF('[[3,4],[4,5]]');
    2. +--------------------------------------------+
    3. | JSON_ARRAY(4,5) MEMBER OF('[[3,4],[4,5]]') |
    4. +--------------------------------------------+
    5. |                                          1 |
    6. +--------------------------------------------+
    7. 1 row in set (0.00 sec)

    Any JSON objects used as values to be tested or which appear in the target array must be coerced to the correct type using CAST(... AS JSON) or JSON_OBJECT(). In addition, a target array containing JSON objects must itself be cast using JSON_ARRAY. This is demonstrated in the following sequence of statements:

    1. mysql> SET @a = CAST('{"a":1}' AS JSON);
    2. Query OK, 0 rows affected (0.00 sec)
    3.  
    4. mysql> SET @b = JSON_OBJECT("b", 2);
    5. Query OK, 0 rows affected (0.00 sec)
    6.  
    7. mysql> SET @c = JSON_ARRAY(17, @b, "abc", @a, 23);
    8. Query OK, 0 rows affected (0.00 sec)
    9.  
    10. mysql> SELECT @a MEMBER OF(@c), @b MEMBER OF(@c);
    11. +------------------+------------------+
    12. | @a MEMBER OF(@c) | @b MEMBER OF(@c) |
    13. +------------------+------------------+
    14. |                1 |                1 |
    15. +------------------+------------------+
    16. 1 row in set (0.00 sec)

    The MEMBER OF() operator was added in MySQL 8.0.17.


Find a PHP function

Document created the 26/06/2006, last modified the 26/10/2018
Source of the printed document:https://www.gaudry.be/en/mysql-rf-json-search-functions.html

The infobrol is a personal site whose content is my sole responsibility. The text is available under CreativeCommons license (BY-NC-SA). More info on the terms of use and the author.

References

  1. View the html document Language of the document:en Manuel MySQL : https://dev.mysql.com/

These references and links indicate documents consulted during the writing of this page, or which may provide additional information, but the authors of these sources can not be held responsible for the content of this page.
The author This site is solely responsible for the way in which the various concepts, and the freedoms that are taken with the reference works, are presented here. Remember that you must cross multiple source information to reduce the risk of errors.

Contents Haut