Table of Contents
为什么选择 MySQL 的 JSON 功能?
创建 JSON 数据
存储 JSON 数据
从 JSON 数据中提取数据
修改 JSON 数据
删除键值对
在 JSON 数据中搜索
JSON 数据聚合
验证 JSON 数据
格式化 JSON 输出
其他 JSON 函数
Home Database Mysql Tutorial Using JSON in MySQL

Using JSON in MySQL

Apr 08, 2025 pm 02:39 PM
mysql ai Data formatting key value pair Why 2025

在现代应用开发中,有效管理半结构化数据至关重要。MySQL 5.7 版本及以上版本内置了对 JSON 数据类型的支持,为关系型数据库中存储、查询和操作这类数据提供了强有力的工具。本文将介绍 MySQL 提供的核心 JSON 函数,并结合实际案例进行讲解,帮助您快速上手。

为什么选择 MySQL 的 JSON 功能?

在关系型数据库中使用 JSON 数据类型,可以简化半结构化或层级数据的处理流程,带来诸多优势:

  • 灵活性: JSON 结构支持动态、层级数据的灵活存储。
  • 内置函数: MySQL 提供高效的 JSON 数据查询、更新和验证函数。
  • 集成性: 可以将关系型数据与 JSON 对象结合,实现混合数据模型。
  1. 创建 JSON 数据

利用 JSON_OBJECT()JSON_ARRAY() 函数,可以方便地构建 JSON 对象或数组。

示例:

SELECT 
    JSON_OBJECT('id', 1, 'name', 'Alice', 'roles', JSON_ARRAY('admin', 'editor')) AS json_data;
Copy after login

输出:

{"id": 1, "name": "Alice", "roles": ["admin", "editor"]}
Copy after login
  1. 存储 JSON 数据

使用 JSON 数据类型定义数据库列,即可存储 JSON 数据。

示例:

CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    details JSON NOT NULL
);

INSERT INTO users (details) 
VALUES ('{"name": "Bob", "age": 30, "roles": ["viewer", "editor"]}');
Copy after login
  1. 从 JSON 数据中提取数据

MySQL 提供多种函数用于从 JSON 文档中提取数据:

  • JSON_EXTRACT():使用 JSONPath 表达式获取指定值。
  • -> 运算符:JSON_EXTRACT() 的简写形式。

示例:

SELECT 
    JSON_EXTRACT(details, '$.name') AS name,
    details->'$.age' AS age
FROM users;
Copy after login

输出:

在 MySQL 中使用 JSON

  1. 修改 JSON 数据

以下函数用于更新或添加 JSON 数据元素:

  • JSON_SET():插入或更新键值对。
  • JSON_INSERT():仅当键不存在时插入。
  • JSON_REPLACE():仅更新已存在的键值对。

示例:

UPDATE users
SET details = JSON_SET(details, '$.city', 'New York')
WHERE id = 1;

SELECT details FROM users;
Copy after login

输出:

{"name": "Bob", "age": 30, "roles": ["viewer", "editor"], "city": "New York"}
Copy after login
  1. 删除键值对

使用 JSON_REMOVE() 函数删除 JSON 文档中的元素。

示例:

UPDATE users
SET details = JSON_REMOVE(details, '$.roles')
WHERE id = 1;

SELECT details FROM users;
Copy after login

输出:

{"name": "Bob", "age": 30, "city": "New York"}
Copy after login
  1. 在 JSON 数据中搜索

JSON_CONTAINS() 函数用于检查 JSON 文档是否包含特定值。

示例:

SELECT 
    JSON_CONTAINS(details, '"New York"', '$.city') AS has_city
FROM users;
Copy after login

输出:

在 MySQL 中使用 JSON

  1. JSON 数据聚合

JSON_ARRAYAGG()JSON_OBJECTAGG() 函数可以将查询结果聚合为 JSON 结构。

示例:

SELECT 
    JSON_ARRAYAGG(name) AS names
FROM (
    SELECT JSON_EXTRACT(details, '$.name') AS name FROM users
) AS subquery;
Copy after login

输出:

["Bob"]
Copy after login
  1. 验证 JSON 数据

JSON_VALID() 函数用于检查字符串是否为有效的 JSON 数据。

示例:

SELECT 
    JSON_VALID('{"key": "value"}') AS is_valid,
    JSON_VALID('invalid json') AS is_invalid;
Copy after login

输出:

在 MySQL 中使用 JSON

  1. 格式化 JSON 输出

JSON_PRETTY() 函数将 JSON 数据格式化为易于阅读的格式。

示例:

SELECT JSON_PRETTY(details) AS pretty_json FROM users;
Copy after login

输出:

{
    "name": "Bob",
    "age": 30,
    "city": "New York"
}
Copy after login

其他 JSON 函数

MySQL 提供了丰富的 JSON 函数,本文仅介绍了部分常用函数。其他函数包括:JSON_ARRAY_APPEND()JSON_ARRAY_INSERT()JSON_CONTAINS_PATH()JSON_DEPTH()JSON_KEYS()JSON_LENGTH()JSON_MERGE_PATCH()JSON_MERGE_PRESERVE()JSON_OVERLAPS()JSON_QUOTE()JSON_SEARCH()JSON_STORAGE_FREE()JSON_STORAGE_SIZE()JSON_TABLE()JSON_TYPE()JSON_UNQUOTE() 等。

MySQL 的 JSON 函数为关系型数据库中半结构化数据的管理提供了强大的支持,简化了 JSON 数据的存储、查询和操作,为数据库设计提供了新的思路。 熟练掌握这些函数,将极大地提高开发效率。

The above is the detailed content of Using JSON in MySQL. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1659
14
PHP Tutorial
1258
29
C# Tutorial
1232
24
How to use the chrono library in C? How to use the chrono library in C? Apr 28, 2025 pm 10:18 PM

Using the chrono library in C can allow you to control time and time intervals more accurately. Let's explore the charm of this library. C's chrono library is part of the standard library, which provides a modern way to deal with time and time intervals. For programmers who have suffered from time.h and ctime, chrono is undoubtedly a boon. It not only improves the readability and maintainability of the code, but also provides higher accuracy and flexibility. Let's start with the basics. The chrono library mainly includes the following key components: std::chrono::system_clock: represents the system clock, used to obtain the current time. std::chron

How to understand DMA operations in C? How to understand DMA operations in C? Apr 28, 2025 pm 10:09 PM

DMA in C refers to DirectMemoryAccess, a direct memory access technology, allowing hardware devices to directly transmit data to memory without CPU intervention. 1) DMA operation is highly dependent on hardware devices and drivers, and the implementation method varies from system to system. 2) Direct access to memory may bring security risks, and the correctness and security of the code must be ensured. 3) DMA can improve performance, but improper use may lead to degradation of system performance. Through practice and learning, we can master the skills of using DMA and maximize its effectiveness in scenarios such as high-speed data transmission and real-time signal processing.

How to measure thread performance in C? How to measure thread performance in C? Apr 28, 2025 pm 10:21 PM

Measuring thread performance in C can use the timing tools, performance analysis tools, and custom timers in the standard library. 1. Use the library to measure execution time. 2. Use gprof for performance analysis. The steps include adding the -pg option during compilation, running the program to generate a gmon.out file, and generating a performance report. 3. Use Valgrind's Callgrind module to perform more detailed analysis. The steps include running the program to generate the callgrind.out file and viewing the results using kcachegrind. 4. Custom timers can flexibly measure the execution time of a specific code segment. These methods help to fully understand thread performance and optimize code.

An efficient way to batch insert data in MySQL An efficient way to batch insert data in MySQL Apr 29, 2025 pm 04:18 PM

Efficient methods for batch inserting data in MySQL include: 1. Using INSERTINTO...VALUES syntax, 2. Using LOADDATAINFILE command, 3. Using transaction processing, 4. Adjust batch size, 5. Disable indexing, 6. Using INSERTIGNORE or INSERT...ONDUPLICATEKEYUPDATE, these methods can significantly improve database operation efficiency.

How to handle high DPI display in C? How to handle high DPI display in C? Apr 28, 2025 pm 09:57 PM

Handling high DPI display in C can be achieved through the following steps: 1) Understand DPI and scaling, use the operating system API to obtain DPI information and adjust the graphics output; 2) Handle cross-platform compatibility, use cross-platform graphics libraries such as SDL or Qt; 3) Perform performance optimization, improve performance through cache, hardware acceleration, and dynamic adjustment of the details level; 4) Solve common problems, such as blurred text and interface elements are too small, and solve by correctly applying DPI scaling.

What is real-time operating system programming in C? What is real-time operating system programming in C? Apr 28, 2025 pm 10:15 PM

C performs well in real-time operating system (RTOS) programming, providing efficient execution efficiency and precise time management. 1) C Meet the needs of RTOS through direct operation of hardware resources and efficient memory management. 2) Using object-oriented features, C can design a flexible task scheduling system. 3) C supports efficient interrupt processing, but dynamic memory allocation and exception processing must be avoided to ensure real-time. 4) Template programming and inline functions help in performance optimization. 5) In practical applications, C can be used to implement an efficient logging system.

How to configure the character set and collation rules of MySQL How to configure the character set and collation rules of MySQL Apr 29, 2025 pm 04:06 PM

Methods for configuring character sets and collations in MySQL include: 1. Setting the character sets and collations at the server level: SETNAMES'utf8'; SETCHARACTERSETutf8; SETCOLLATION_CONNECTION='utf8_general_ci'; 2. Create a database that uses specific character sets and collations: CREATEDATABASEexample_dbCHARACTERSETutf8COLLATEutf8_general_ci; 3. Specify character sets and collations when creating a table: CREATETABLEexample_table(idINT

How does deepseek official website achieve the effect of penetrating mouse scroll event? How does deepseek official website achieve the effect of penetrating mouse scroll event? Apr 30, 2025 pm 03:21 PM

How to achieve the effect of mouse scrolling event penetration? When we browse the web, we often encounter some special interaction designs. For example, on deepseek official website, �...

See all articles