Home >Database >Mysql Tutorial >How can I Query JSON Data in MySQL Based on Specific Field Values?

How can I Query JSON Data in MySQL Based on Specific Field Values?

Barbara Streisand
Barbara StreisandOriginal
2024-10-26 10:34:02457browse

How can I Query JSON Data in MySQL Based on Specific Field Values?

Querying JSON Data in MySQL

Problem:

You have a MySQL table with a column that stores JSON objects. You need to run queries that filter results based on specific JSON field values.

Solution: Using json_extract Function

MySQL 5.7 and later introduced the json_extract function, which allows you to extract specific values from JSON objects stored in a column. This allows you to perform queries like the following:

<code class="sql">SELECT user_id, json_data
FROM articles
WHERE json_extract(json_data, '$.title') LIKE '%CPU%';</code>

Example:

Consider the following table:

<code class="sql">CREATE TABLE articles (
  id int NOT NULL,
  user_id int NOT NULL,
  json_data json NOT NULL
);
INSERT INTO articles (id, user_id, json_data) VALUES
  (1, 1, '{"url":"https://www.cpubenchmark.net/","title": "CPU Benchmarks"}'),
  (2, 1, '{"url":"http://www.ebay.com/sch/CPUs-Processors-/164/i.html","title": "Computer and Processors"}'),
  (3, 2, '{"url":"https://www.youtube.com/watch?v=tntOCGkgt98","title": "Funny Cats Compilation"}');</code>

Running the query shown above will return the following result:

<code class="sql">+---------+--------------------------------------------------------------------------------------------------+
| user_id | json_data                                                                                        |
+---------+--------------------------------------------------------------------------------------------------+
|       1 | {"url":"https://www.cpubenchmark.net/","title": "CPU Benchmarks"}                                |
+---------+--------------------------------------------------------------------------------------------------+</code>

This demonstrates how the json_extract function can be used to filter JSON data in MySQL.

The above is the detailed content of How can I Query JSON Data in MySQL Based on Specific Field Values?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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