Table of Contents
Preparation
JSON object basic operation
More operations
Home Database Mysql Tutorial How to use JSON type fields in MySQL

How to use JSON type fields in MySQL

Apr 17, 2023 pm 06:52 PM
mysql json

Test environment: MySQL8.0.19

Preparation

CREATE TABLE json_demo ( 
	`id` INT ( 11 ) NOT NULL PRIMARY KEY, 
	`content` json NOT NULL 
);
INSERT INTO json_demo ( id, content )
VALUES
	/*这条是数组*/
	( 1, '[{"key": 1, "order": 1, "value": "34252"},{"key": 2, "order": 2, "value": "23423"}]' ),
	/*这条是数组*/
	( 2, '[{"key": 4, "order": 4, "value": "234"},{"key": 5, "order": 5, "value": "234324523"}]' ),
	/*这条是对象*/
	( 3, '{"key": 3, "order": 3, "value": "43242"}' ),
	/*这条是对象*/
	( 4, '{"key": 6, "order": 6, "value": "5423"}' );
Copy after login

JSON object basic operation

Query the specified field value

/* 基础查询 */
SELECT
	content -> '$.key' AS 'key',
	JSON_EXTRACT(content, '$.key') AS 'key2',
	content -> '$.value' AS 'value',
	JSON_EXTRACT(content, '$.value') AS 'value2',
	content ->> '$.value' AS 'value3',
	JSON_UNQUOTE(JSON_EXTRACT(content, '$.value')) AS 'value4'
FROM
	json_demo 
WHERE
	id > 2;
Copy after login

How to use JSON type fields in MySQL

TIPS:

  • ##-> and ->> are the syntax designed by MySQL , among which -> is supported in MySQL5.7, and ->> is supported in MySQL8.0.

  • -> Equivalent to JSON_EXTRACT(), when the query field is a string, the return value will also have "".

  • ->> Equivalent to JSON_UNQUOTE(JSON_EXTRACT()), when the query field is a string, the return value will not have "".

Used for conditional query

content -> '$.key' can be regarded as a field, and the operations that can be performed on a field are basically He can do it.

SELECT
	id,
	content -> '$.key' AS 'key',
	content ->> '$.value' AS 'value3'
FROM
	json_demo 
WHERE
	id > 2
	AND content -> '$.key' > 1
	AND content -> '$.value' like '%2%';
Copy after login

How to use JSON type fields in MySQL

Modify the specified field value

/* 修改 */
UPDATE json_demo 
SET content = JSON_REPLACE(
	content,
	/* 将content.key值 + 1 */
	'$.key', content -> '$.key' + 1,
	/* 将content.value值后拼接'abc' */
	'$.value', concat(content ->> '$.value', 'abc')
) WHERE id = 3;
/* JSON_SET也可以 */
UPDATE json_demo 
SET content = JSON_SET(
	content,
	/* 将content.key值 + 1 */
	'$.key', content -> '$.key' + 1,
	/* 将content.value值后拼接'abc' */
	'$.value', concat(content ->> '$.value', 'abc')
) WHERE id = 3;
/* 查询修改结果 */
SELECT id,content,content -> '$.key' AS 'key',content ->> '$.value' AS 'value3'
FROM json_demo WHERE id = 3;
/* 重新赋值 */
UPDATE json_demo SET 
content = JSON_REPLACE(content,'$.key',3,'$.value','43242') WHERE id = 3;
Copy after login

How to use JSON type fields in MySQL

TIPS:

  • Both JSON_REPLACE and JSON_SET can be used to modify the value of a certain field. The difference is that when JSON_REPLACE replaces a non-existent attribute, the operation is invalid; while JSON_SET will insert the non-existent attribute.

  • So JSON_SET can also be used to append attributes, similar to JSON_INSERT. The difference is that JSON_INSERT operation will fail if an existing attribute is inserted, while JSON_SET will replace it.

Append elements

UPDATE json_demo 
SET content = JSON_INSERT(content, '$.key', 234)
WHERE id = 3;

SELECT id,content,content -> '$.key' AS 'key' FROM json_demo WHERE id = 3;

UPDATE json_demo 
SET content = JSON_INSERT(content, '$.temp', 234)
WHERE id = 3;

SELECT id,content,content -> '$.key' AS 'key' FROM json_demo WHERE id = 3;

UPDATE json_demo 
SET content = JSON_SET(content, '$.temp2', 432)
WHERE id = 3;

SELECT id,content,content -> '$.key' AS 'key' FROM json_demo WHERE id = 3;
Copy after login

How to use JSON type fields in MySQL##JSON array operation

Query specification Field value

SELECT
	id,
	content -> '$[*].key' AS 'key',
	content ->> '$[*].value' AS 'value',
	content -> '$[0].key' AS 'key2',
	content ->> '$[0].value' AS 'value2',
	/* 查询数组长度 */
	JSON_LENGTH(content) AS 'length'
FROM
	json_demo 
WHERE
	id < 3;
Copy after login

How to use JSON type fields in MySQL

is used for conditional query

SELECT
	id,
	content -> &#39;$[*].key&#39; AS &#39;key&#39;,
	content ->> &#39;$[*].value&#39; AS &#39;value&#39;
FROM
	json_demo 
WHERE
	id < 3
	/* content.value的值中存在like&#39;%34%&#39;的值 */
	AND content ->> &#39;$[*].value&#39; like &#39;%34%&#39;
	/* content.key的值中有4 */
	AND JSON_OVERLAPS(content ->> &#39;$[*].key&#39;, &#39;4&#39; );
Copy after login

How to use JSON type fields in MySQL

Modify the specified field value

The basic operations are not much different from the JSON object, that is, add the corresponding index bit '$[0]' after '$', and specify all '$[*] '. If the array contains an array, you can specify the deep array elements through '$[1][2][3]'.

How to use JSON type fields in MySQL

Append elements

Both JSON_ARRAY_APPEND and JSON_ARRAY_INSERT can append array elements. The difference is that JSON_ARRAY_APPEND does not need to specify the index bit, in which case it will be appended to the last position; JSON_ARRAY_INSERT must specify the index bit, and an error will be reported if not specified.

JSON_ARRAY_APPEND is appended after the specified index bit, while JSON_ARRAY_INSERT is inserted in front of the specified index bit.

More operations

##JSON_ARRAY_INSERT( )Insert into JSON arrayJSON_CONTAINS()Whether the JSON document contains a specific object in the pathJSON_CONTAINS_PATH()Whether the JSON document contains any data in the pathJSON_DEPTH()The maximum depth of the JSON documentJSON_EXTRACT()Return data from JSON documentJSON_INSERT()Insert data into JSON documentJSON_KEYS()Key array in JSON documentJSON_LENGTH()In JSON document Number of elements JSON_MERGE() (deprecated) Merge JSON documents, retaining duplicate keys. Deprecated synonyms for JSON_MERGE_PRESERVE()JSON_MERGE_PATCH()Merge JSON documents, replacing values ​​for duplicate keys JSON_MERGE_PRESERVE()Merge JSON documents, retaining duplicate keysJSON_OBJECT()Create JSON objectJSON_OVERLAPS() (Introduced in 8.0.17) Compares two JSON documents and returns TRUE (1) if they have any key-value pairs or array elements in common, otherwise returns FALSE (0) JSON_PRETTY()Print JSON document in an easy-to-read format##JSON_QUOTE()JSON_REMOVE()JSON_REPLACE()JSON_SCHEMA_VALID() (Introduced in 8.0.17) JSON_SCHEMA_VALIDATION_REPORT() (Introduced in 8.0.17) JSON_SEARCH()##JSON_SET()will Data inserted into JSON documentJSON_STORAGE_FREE()Free space in binary representation of JSON column value after partial updateJSON_STORAGE_SIZE()The space used to store the binary representation of the JSON document JSON_TABLE() Returns data from a JSON expression as Relational tableJSON_TYPE()JSON value typeJSON_UNQUOTE()Dereference JSON ValueJSON_VALID()Whether the JSON value is validExtracts a value from the JSON document at the location pointed to by the supplied path; returns this value as VARCHAR (512) or the specified type Returns true (1) if the first operand matches any element of the JSON array passed as the second operand, false (0) otherwise
Name Description
JSON_ARRAY() Create a JSON array
JSON_ARRAY_APPEND() Append data to a JSON document
Reference JSON document
Remove data from JSON document
Replace values ​​in JSON documents
Validate JSON documents against the JSON schema; if the document is validated against the schema, then Returns TRUE/1; otherwise, returns FALSE/0.
Validates a JSON document against a JSON schema; returns a report on the validation results in JSON format, including success or failure and failure Reason
The path of the value in the JSON document
##JSON_VALUE() (introduced in 8.0.21)
MEMBER OF() (8.0.17 Introduced)

The above is the detailed content of How to use JSON type fields 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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

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)

MySQL: Simple Concepts for Easy Learning MySQL: Simple Concepts for Easy Learning Apr 10, 2025 am 09:29 AM

MySQL is an open source relational database management system. 1) Create database and tables: Use the CREATEDATABASE and CREATETABLE commands. 2) Basic operations: INSERT, UPDATE, DELETE and SELECT. 3) Advanced operations: JOIN, subquery and transaction processing. 4) Debugging skills: Check syntax, data type and permissions. 5) Optimization suggestions: Use indexes, avoid SELECT* and use transactions.

How to open phpmyadmin How to open phpmyadmin Apr 10, 2025 pm 10:51 PM

You can open phpMyAdmin through the following steps: 1. Log in to the website control panel; 2. Find and click the phpMyAdmin icon; 3. Enter MySQL credentials; 4. Click "Login".

MySQL: An Introduction to the World's Most Popular Database MySQL: An Introduction to the World's Most Popular Database Apr 12, 2025 am 12:18 AM

MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.

Why Use MySQL? Benefits and Advantages Why Use MySQL? Benefits and Advantages Apr 12, 2025 am 12:17 AM

MySQL is chosen for its performance, reliability, ease of use, and community support. 1.MySQL provides efficient data storage and retrieval functions, supporting multiple data types and advanced query operations. 2. Adopt client-server architecture and multiple storage engines to support transaction and query optimization. 3. Easy to use, supports a variety of operating systems and programming languages. 4. Have strong community support and provide rich resources and solutions.

How to use single threaded redis How to use single threaded redis Apr 10, 2025 pm 07:12 PM

Redis uses a single threaded architecture to provide high performance, simplicity, and consistency. It utilizes I/O multiplexing, event loops, non-blocking I/O, and shared memory to improve concurrency, but with limitations of concurrency limitations, single point of failure, and unsuitable for write-intensive workloads.

MySQL and SQL: Essential Skills for Developers MySQL and SQL: Essential Skills for Developers Apr 10, 2025 am 09:30 AM

MySQL and SQL are essential skills for developers. 1.MySQL is an open source relational database management system, and SQL is the standard language used to manage and operate databases. 2.MySQL supports multiple storage engines through efficient data storage and retrieval functions, and SQL completes complex data operations through simple statements. 3. Examples of usage include basic queries and advanced queries, such as filtering and sorting by condition. 4. Common errors include syntax errors and performance issues, which can be optimized by checking SQL statements and using EXPLAIN commands. 5. Performance optimization techniques include using indexes, avoiding full table scanning, optimizing JOIN operations and improving code readability.

MySQL's Place: Databases and Programming MySQL's Place: Databases and Programming Apr 13, 2025 am 12:18 AM

MySQL's position in databases and programming is very important. It is an open source relational database management system that is widely used in various application scenarios. 1) MySQL provides efficient data storage, organization and retrieval functions, supporting Web, mobile and enterprise-level systems. 2) It uses a client-server architecture, supports multiple storage engines and index optimization. 3) Basic usages include creating tables and inserting data, and advanced usages involve multi-table JOINs and complex queries. 4) Frequently asked questions such as SQL syntax errors and performance issues can be debugged through the EXPLAIN command and slow query log. 5) Performance optimization methods include rational use of indexes, optimized query and use of caches. Best practices include using transactions and PreparedStatemen

How to recover data after SQL deletes rows How to recover data after SQL deletes rows Apr 09, 2025 pm 12:21 PM

Recovering deleted rows directly from the database is usually impossible unless there is a backup or transaction rollback mechanism. Key point: Transaction rollback: Execute ROLLBACK before the transaction is committed to recover data. Backup: Regular backup of the database can be used to quickly restore data. Database snapshot: You can create a read-only copy of the database and restore the data after the data is deleted accidentally. Use DELETE statement with caution: Check the conditions carefully to avoid accidentally deleting data. Use the WHERE clause: explicitly specify the data to be deleted. Use the test environment: Test before performing a DELETE operation.

See all articles