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

How to Efficiently Search for Elements within JSON Arrays in MySQL?

Susan Sarandon
Release: 2024-11-29 11:59:09
Original
301 people have browsed it

How to Efficiently Search for Elements within JSON Arrays in MySQL?

Searching JSON Arrays in MySQL

Suppose you have a MySQL table with a JSON column named "data" containing an array. You wish to retrieve all rows where one of the array elements is greater than 2.

The query

SELECT * from my_table
WHERE JSON_EXTRACT(data, '$[*]') > 2;
Copy after login

returns an incorrect result because it always evaluates to true, regardless of the array's values.

To search for an integer in an array:

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

To search for a string in an array:

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

For your scenario, use the query:

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

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

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