Home  >  Article  >  Database  >  How to Retrieve a Specific Object from a JSON Column in MySQL Based on Key-Value Pair?

How to Retrieve a Specific Object from a JSON Column in MySQL Based on Key-Value Pair?

Susan Sarandon
Susan SarandonOriginal
2024-11-03 15:09:30443browse

How to Retrieve a Specific Object from a JSON Column in MySQL Based on Key-Value Pair?

MySQL JSON: Searching Objects Based on Key Values

MySQL tables often utilize JSON columns to store complex data structures. When working with JSON, a common task is to retrieve a specific object based on a key-value pair. However, finding the object directly may not always be straightforward.

JSON Schema Example:

Consider the following schema:

<code class="sql">CREATE TABLE `fields` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `label` varchar(64) COLLATE utf8mb4_unicode_ci NOT NULL,
  `options` json DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;</code>

With sample data:

<code class="sql">INSERT INTO `fields` (label, options) VALUES
(
  'My Field', 
  '[{"text": "Grass", "value": "1"}, {"text": "Synthetic (New Type - Soft)", "value": "2"}, {"text": "Synthetic  (Old Type - Hard)", "value": "3"}, {"text": "Gravel", "value": "5"}, {"text": "Clay", "value": "6"}, {"text": "Sand", "value": "7"}, {"text": "Grass/Synthetic Mix", "value": "8"}]'
);</code>

Problem:

Suppose we want to retrieve the string "Grass" from the options JSON array, knowing that its corresponding "value" is "1." Using JSON_EXTRACT() alone requires the index of the array, which may not be readily available.

Solution 1: Using JSON_SEARCH() and Horrible String Manipulation

This approach combines JSON_SEARCH() to partially find the index and then removes unwanted parts from the string:

<code class="sql">SELECT
JSON_EXTRACT(`options`,CONCAT('$[',REPLACE(REPLACE(JSON_SEARCH(`options`, 'one', '1'), '"$[', ''), '].value"', ''), '].text'))
from `fields`;</code>

Solution 2: Using JSON_TABLE()

MySQL 8.0 introduces JSON_TABLE() to simplify this task:

<code class="sql">select field_options.* from fields cross join 
json_table(fields.options, 
'$[*]' columns(
  text text path '$.text',
  value text path '$.value'
 )
) as field_options 
where field_options.value = 1;</code>

Alternative Approach: Relational Data Model

For simpler data structures like this example, consider storing the data in a relational table with columns for key and value pairs, allowing for direct search:

<code class="sql">SELECT * FROM field_options WHERE value = '1';</code>

The above is the detailed content of How to Retrieve a Specific Object from a JSON Column in MySQL Based on Key-Value Pair?. 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