Home > Database > Mysql Tutorial > How Can I Search for Elements Within JSON Arrays in MySQL?

How Can I Search for Elements Within JSON Arrays in MySQL?

Patricia Arquette
Release: 2024-12-05 00:41:11
Original
753 people have browsed it

How Can I Search for Elements Within JSON Arrays in MySQL?

Searching JSON Arrays in MySQL: A Comprehensive Guide

Searching within JSON arrays in MySQL can be achieved using the JSON_CONTAINS function. This function takes the JSON array, an array element, and a path expression as parameters and returns a Boolean value indicating whether the element is present in the array.

Searching for Integers in Arrays

To search for specific integers in an array of integers, use the following syntax:

JSON_CONTAINS(data, 'element', '$')
Copy after login
Copy after login

For example:

  JSON_CONTAINS('[1,2,3,4,5]','7','$') Returns: 0
  JSON_CONTAINS('[1,2,3,4,5]','1','$') Returns: 1
Copy after login

Searching for Strings in Arrays

Similar to searching for integers, to search for strings in an array of strings, use this syntax:

JSON_CONTAINS(data, 'element', '$')
Copy after login
Copy after login

For example:

  JSON_CONTAINS('["a","2","c","4","x"]','"x"','$') Returns: 1
  JSON_CONTAINS('["1","2","3","4","5"]','"7"','$') Returns: 0
Copy after login

Applying the Knowledge

To answer the original question, you can search for array elements greater than 2 with the following query:

SELECT * from my_table
WHERE JSON_CONTAINS(data, '2', '$');
Copy after login

This query will return all rows where the data column contains an array with an element greater than 2.

The above is the detailed content of How Can I Search for Elements Within JSON Arrays in MySQL?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template