Using JSON in MySQL
在现代应用开发中,有效管理半结构化数据至关重要。MySQL 5.7 版本及以上版本内置了对 JSON 数据类型的支持,为关系型数据库中存储、查询和操作这类数据提供了强有力的工具。本文将介绍 MySQL 提供的核心 JSON 函数,并结合实际案例进行讲解,帮助您快速上手。
为什么选择 MySQL 的 JSON 功能?
在关系型数据库中使用 JSON 数据类型,可以简化半结构化或层级数据的处理流程,带来诸多优势:
- 灵活性: JSON 结构支持动态、层级数据的灵活存储。
- 内置函数: MySQL 提供高效的 JSON 数据查询、更新和验证函数。
- 集成性: 可以将关系型数据与 JSON 对象结合,实现混合数据模型。
-
创建 JSON 数据
利用 JSON_OBJECT()
和 JSON_ARRAY()
函数,可以方便地构建 JSON 对象或数组。
示例:
SELECT JSON_OBJECT('id', 1, 'name', 'Alice', 'roles', JSON_ARRAY('admin', 'editor')) AS json_data;
输出:
{"id": 1, "name": "Alice", "roles": ["admin", "editor"]}
-
存储 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"]}');
-
从 JSON 数据中提取数据
MySQL 提供多种函数用于从 JSON 文档中提取数据:
JSON_EXTRACT()
:使用 JSONPath 表达式获取指定值。->
运算符:JSON_EXTRACT()
的简写形式。
示例:
SELECT JSON_EXTRACT(details, '$.name') AS name, details->'$.age' AS age FROM users;
输出:
-
修改 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;
输出:
{"name": "Bob", "age": 30, "roles": ["viewer", "editor"], "city": "New York"}
-
删除键值对
使用 JSON_REMOVE()
函数删除 JSON 文档中的元素。
示例:
UPDATE users SET details = JSON_REMOVE(details, '$.roles') WHERE id = 1; SELECT details FROM users;
输出:
{"name": "Bob", "age": 30, "city": "New York"}
-
在 JSON 数据中搜索
JSON_CONTAINS()
函数用于检查 JSON 文档是否包含特定值。
示例:
SELECT JSON_CONTAINS(details, '"New York"', '$.city') AS has_city FROM users;
输出:
-
JSON 数据聚合
JSON_ARRAYAGG()
和 JSON_OBJECTAGG()
函数可以将查询结果聚合为 JSON 结构。
示例:
SELECT JSON_ARRAYAGG(name) AS names FROM ( SELECT JSON_EXTRACT(details, '$.name') AS name FROM users ) AS subquery;
输出:
["Bob"]
-
验证 JSON 数据
JSON_VALID()
函数用于检查字符串是否为有效的 JSON 数据。
示例:
SELECT JSON_VALID('{"key": "value"}') AS is_valid, JSON_VALID('invalid json') AS is_invalid;
输出:
-
格式化 JSON 输出
JSON_PRETTY()
函数将 JSON 数据格式化为易于阅读的格式。
示例:
SELECT JSON_PRETTY(details) AS pretty_json FROM users;
输出:
{ "name": "Bob", "age": 30, "city": "New York" }
其他 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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Mark Cerny, chief architect of SonyInteractiveEntertainment (SIE, Sony Interactive Entertainment), has released more hardware details of next-generation host PlayStation5Pro (PS5Pro), including a performance upgraded AMDRDNA2.x architecture GPU, and a machine learning/artificial intelligence program code-named "Amethylst" with AMD. The focus of PS5Pro performance improvement is still on three pillars, including a more powerful GPU, advanced ray tracing and AI-powered PSSR super-resolution function. GPU adopts a customized AMDRDNA2 architecture, which Sony named RDNA2.x, and it has some RDNA3 architecture.

The CentOS shutdown command is shutdown, and the syntax is shutdown [Options] Time [Information]. Options include: -h Stop the system immediately; -P Turn off the power after shutdown; -r restart; -t Waiting time. Times can be specified as immediate (now), minutes ( minutes), or a specific time (hh:mm). Added information can be displayed in system messages.

Apple's iPhone 17 may usher in a major upgrade to cope with the impact of strong competitors such as Huawei and Xiaomi in China. According to the digital blogger @Digital Chat Station, the standard version of iPhone 17 is expected to be equipped with a high refresh rate screen for the first time, significantly improving the user experience. This move marks the fact that Apple has finally delegated high refresh rate technology to the standard version after five years. At present, the iPhone 16 is the only flagship phone with a 60Hz screen in the 6,000 yuan price range, and it seems a bit behind. Although the standard version of the iPhone 17 will have a high refresh rate screen, there are still differences compared to the Pro version, such as the bezel design still does not achieve the ultra-narrow bezel effect of the Pro version. What is more worth noting is that the iPhone 17 Pro series will adopt a brand new and more

Microsoft's improvements to Windows search functions have been tested on some Windows Insider channels in the EU. Previously, the integrated Windows search function was criticized by users and had poor experience. This update splits the search function into two parts: local search and Bing-based web search to improve user experience. The new version of the search interface performs local file search by default. If you need to search online, you need to click the "Microsoft BingWebSearch" tab to switch. After switching, the search bar will display "Microsoft BingWebSearch:", where users can enter keywords. This move effectively avoids the mixing of local search results with Bing search results

Xiaomi Auto’s first anniversary celebration will give car owners a New Year gift! After the delivery volume exceeded 130,000 vehicles last year, Xiaomi Auto’s official Weibo announced that it will give Lei Jun’s classic quotation “AreyouOK?” to every Xiaomi SU7 owner and prospective owner. The number is limited and free to receive it! Activity time: 4 pm on December 28, 2024 to 23:59:59 on January 20, 2025. Users who purchase a car or complete an order before 23:59:59 on December 31, 2024 can get a set of four-piece "AreyouOK?" valve core caps for free. This valve core cap was first released in September this year and is made of bright yellow PVC and brass material. The brass core is directly embedded to ensure safe driving and not easy to fall off. Widely used,

MySQL and Oracle selection should be based on cost, performance, complexity and functional requirements: 1. MySQL is suitable for projects with limited budgets, is simple to install, and is suitable for small to medium-sized applications. 2. Oracle is suitable for large enterprises and performs excellently in handling large-scale data and high concurrent requests, but is costly and complex in configuration.

CentOS will be shut down in 2024 because its upstream distribution, RHEL 8, has been shut down. This shutdown will affect the CentOS 8 system, preventing it from continuing to receive updates. Users should plan for migration, and recommended options include CentOS Stream, AlmaLinux, and Rocky Linux to keep the system safe and stable.

Zookeeper performance tuning on CentOS can start from multiple aspects, including hardware configuration, operating system optimization, configuration parameter adjustment, monitoring and maintenance, etc. Here are some specific tuning methods: SSD is recommended for hardware configuration: Since Zookeeper's data is written to disk, it is highly recommended to use SSD to improve I/O performance. Enough memory: Allocate enough memory resources to Zookeeper to avoid frequent disk read and write. Multi-core CPU: Use multi-core CPU to ensure that Zookeeper can process it in parallel.
