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 8.0.17 installation and simple configuration tutorial under macOS

If you don’t understand what I wrote, there may b...

Docker implements container port binding local port

Today, I encountered a small problem that after s...

Steps to configure IIS10 under Win10 and support debugging ASP programs

Microsoft IIS IIS (Internet Information Server) i...

How to change the password of mysql5.7.20 under linux CentOS 7.4

After MySQL was upgraded to version 5.7, its secu...

JavaScript singleton mode to implement custom pop-up box

This article shares the specific code of JavaScri...

A complete explanation of MySQL high availability architecture: MHA architecture

Table of contents 1. Introduction 2. Composition ...

How to set mysql5.7 encoding set to utf8mb4

I recently encountered a problem. The emoticons o...

A practical record of checking and processing duplicate MySQL records on site

Table of contents Preface analyze Data Total Repe...

A very detailed summary of communication between Vue components

Table of contents Preface 1. Props, $emit one-way...

How to use Docker to package and deploy images locally

First time using docker to package and deploy ima...

How to install and configure WSL on Windows

What is WSL Quoting a passage from Baidu Encyclop...

MySQL column to row conversion and year-month grouping example

As shown below: SELECT count(DISTINCT(a.rect_id))...

Pure CSS to achieve input box placeholder animation and input verification

For more exciting content, please visit https://g...

Example of implementing skeleton screen with Vue

Table of contents Skeleton screen use Vue archite...