Home > Database > Mysql Tutorial > How to Search for Elements within JSON Arrays in MySQL?

How to Search for Elements within JSON Arrays in MySQL?

Susan Sarandon
Release: 2024-12-02 05:24:10
Original
323 people have browsed it

How to Search for Elements within JSON Arrays in MySQL?

Searching JSON Array Elements in MySQL

Your query attempts to use the JSON_EXTRACT function to compare the entire array with a scalar value, which will always return a non-null result. To search for specific elements within the array, you can utilize the JSON_CONTAINS function.

Searching an Array of Integers:

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

This will return 0 if the array does not contain the value 7 and 1 if it does.

Searching an Array of Strings:

JSON_CONTAINS('["a","2","c","4","x"]','"x"','$')
Copy after login

This will return 1 if the array contains the string "x" and 0 otherwise.

Query for Your Case:

To select all rows where the data column contains an array element greater than 2, use the following query:

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

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

The above is the detailed content of How to 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