MySQL operations: JSON data type operations

MySQL operations: JSON data type operations

In the previous article, we introduced the detailed example of MySQL data storage procedure parameters. Today, let's take a look at the relevant content of MySQL operations on the JSON data type.

Overview

Since version 5.7.8, MySQL has supported the storage and query of JSON structured data, which shows that MySQL is also constantly learning and adding the advantages of NoSQL databases. But MySQL is a relational database after all, and it is still awkward when processing unstructured data such as JSON.

Create a table with a JSON field

First, create a table that contains a field in json format:

CREATE TABLE table_name (
  id INT NOT NULL AUTO_INCREMENT, 
  json_col JSON,
  PRIMARY KEY(id)
);

In the above statement, pay attention to the json_col field, which specifies the data type as JSON.

Insert a simple JSON data

INSERT INTO
  table_name (json_col) 
VALUES
  ('{"City": "Galle", "Description": "Best damn city in the world"}');
  

In the above SQL statement, pay attention to the part after VALUES. Since double quotes are required to identify strings in json format data, the content after VALUES needs to be wrapped in single quotes.

Insert a complex JSON data

INSERT INTO table(col) 
VALUES('{"opening":"Sicilian","variations":["pelikan","dragon","najdorf"]}');

Here, we inserted a json array. The main thing is to pay attention to the problem of single quotes and double quotes.

Modifying JSON Data

In the previous example, we inserted several pieces of JSON data, but if we want to modify a certain content in the JSON data, how can we achieve it? For example, if we add an element to the variations array, we can do this:

UPDATE myjson SET dict=JSON_ARRAY_APPEND(dict,'$.variations','scheveningen') WHERE id = 2;

In this SQL statement, $ represents the JSON field, the dot is used to index the variations field, and then an element is added using the JSON_ARRAY_APPEND function. Now we execute the query:

SELECT * FROM myjson

The result is:

+----+-----------------------------------------------------------------------------------------+
| id | dict |
+---+-----------------------------------------------------------------------------------------+
| 2 | {"opening": "Sicilian", "variations": ["pelikan", "dragon", "najdorf", "scheveningen"]} |
+----+-----------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

For more information about how to obtain JSON data in MySQL, refer to the official link JSON Path Syntax

Create Index

MySQL's JSON format data cannot be indexed directly, but you can work around it by separating the data to be searched into a separate data column and then creating an index on this field. Here is the official example:

mysql> CREATE TABLE jemp (
  -> c JSON,
  -> g INT GENERATED ALWAYS AS (c->"$.id"),
  -> INDEX i (g)
  -> );
Query OK, 0 rows affected (0.28 sec)

mysql> INSERT INTO jemp (c) VALUES
   > ('{"id": "1", "name": "Fred"}'), ('{"id": "2", "name": "Wilma"}'),
   > ('{"id": "3", "name": "Barney"}'), ('{"id": "4", "name": "Betty"}');
Query OK, 4 rows affected (0.04 sec)
Records: 4 Duplicates: 0 Warnings: 0

mysql> SELECT c->>"$.name" AS name
   > FROM jemp WHERE g > 2;
+--------+
| name |
+--------+
| Barney |
| Betty |
+--------+
2 rows in set (0.00 sec)

mysql> EXPLAIN SELECT c->>"$.name" AS name
   > FROM jemp WHERE g > 2\G
*************************** 1. row ***************************
      id: 1
 select_type: SIMPLE
    table: jemp
  partitions: NULL
     type: range
possible_keys: i
     key: i
   key_len: 5
     ref: NULL
     rows: 2
   filtered: 100.00
    Extra: Using where
1 row in set, 1 warning (0.00 sec)

mysql> SHOW WARNINGS\G
*************************** 1. row ***************************
 Level: Note
  Code: 1003
Message: /* select#1 */ select json_unquote(json_extract(`test`.`jemp`.`c`,'$.name'))
AS `name` from `test`.`jemp` where (`test`.`jemp`.`g` > 2)
1 row in set (0.00 sec)

This example is very simple. It takes the id field in the JSON field and separates it into field g. Then, an index is created on field g, and the query condition is also on field g.

Convert string to JSON format

Convert a string in json format to MySQL's JSON type:

SELECT CAST('[1,2,3]' as JSON) ;
SELECT CAST('{"opening":"Sicilian","variations":["pelikan","dragon","najdorf"]}' as JSON);

All MySQL JSON functions

Name Description
JSON_APPEND() Append data to JSON document
JSON_ARRAY() Create JSON array
JSON_ARRAY_APPEND() Append data to JSON document
JSON_ARRAY_INSERT() Insert into JSON array-> Return value from JSON column after evaluating path; equivalent to JSON_EXTRACT().
JSON_CONTAINS() Whether a JSON document contains a specific object at path
JSON_CONTAINS_PATH() Whether JSON document contains any data at path
JSON_DEPTH() Maximum depth of JSON document
JSON_EXTRACT() Return data from JSON document->> Return value from JSON column after evaluating path and unquoting the result; equivalent to JSON_UNQUOTE(JSON_EXTRACT()).
JSON_INSERT() Insert data into JSON document
JSON_KEYS() Array of keys from JSON document
JSON_LENGTH() Number of elements in JSON document
JSON_MERGE() Merge JSON documents, preserving duplicate keys. Deprecated synonym for JSON_MERGE_PRESERVE()
JSON_MERGE_PRESERVE() Merge JSON documents, preserving duplicate keys
JSON_OBJECT() Create JSON object
JSON_QUOTE() Quote JSON document
JSON_REMOVE() Remove data from JSON document
JSON_REPLACE() Replace values ​​in JSON document
JSON_SEARCH() Path to value within JSON document
JSON_SET() Insert data into JSON document
JSON_TYPE() Type of JSON value
JSON_UNQUOTE() Unquote JSON value
JSON_VALID() Whether JSON value is valid

Summarize

The above is all the content of this article about the detailed explanation of JSON data type operations in MySQL. I hope it will be helpful to everyone. Interested friends can continue to refer to this site: Detailed example of MySQL data storage process parameter, brief description of the difference between Redis and MySQL, several important MySQL variables, etc. If there are any deficiencies, please leave a message and point them out. The editor will reply to you in time and make modifications, and strive to provide better articles and reading experience for the majority of programming enthusiasts and workers. Here are some books related to MySQL operation for your reference:

MySQL Database Application from Beginner to Master (2nd Edition) PDF Scanned Version

https://www.jb51.net/books/361239.html

MySQL5 Definitive Guide (3rd Edition) Chinese version PDF scanned version

https://www.jb51.net/books/367031.html

I hope you like it. For more exciting content, please visit: https://www.jb51.net/

You may also be interested in:
  • Compatibility comparison between PostgreSQL and MySQL data types
  • MySQL data type optimization principles
  • Detailed explanation of data types and schema optimization in MySQL
  • Description of the correspondence between MyBatis JdbcType and Oracle and MySql data types
  • In-depth analysis of MySQL data type DECIMAL
  • Detailed explanation of the principles and usage of MySQL data types and field attributes
  • Detailed explanation of basic data types in mysql8.0.19
  • Introduction to MySQL (Part 2) Detailed Explanation of Database Data Types
  • Detailed explanation of the meaning of N and M in the MySQL data type DECIMAL(N,M)
  • MySQL data types full analysis

<<:  Setting up shared folders in Ubuntu virtual machine of VMWare14.0.0

>>:  React-Native environment setup and basic introduction

Recommend

MySQL data type details

Table of contents 1. Numeric Type 1.1 Classificat...

Introduction to Linux system swap space

Swap space is a common aspect of computing today,...

Docker packages the local image and restores it to other machines

1. Use docker images to view all the image files ...

A brief analysis of React's understanding of state

How to define complex components (class component...

How to limit the value range of object keys in TypeScript

When we use TypeScript, we want to use the type s...

MySQL should never write update statements like this

Table of contents Preface cause Phenomenon why? A...

Semanticization of HTML tags (including H5)

introduce HTML provides the contextual structure ...

Introduction to the use of http-equiv attribute in meta tag

meta is an auxiliary tag in the head area of ​​htm...

Detailed explanation of desktop application using Vue3 and Electron

Table of contents Vue CLI builds a Vue project Vu...

Docker deploys Mysql, .Net6, Sqlserver and other containers

Table of contents Install Docker on CentOS 8 1. U...

Javascript Basics: Detailed Explanation of Operators and Flow Control

Table of contents 1. Operator 1.1 Arithmetic oper...

Web page creation question: Image file path

This article is original by 123WORDPRESS.COM Ligh...

JavaScript determines whether the browser is IE

As a front-end developer, I can’t avoid IE’s pitf...

HTML basic summary recommendation (text format)

HTML text formatting tags 標簽 描述 <b> 定義粗體文本 ...