This article brings you the basic JSON operations (code examples) of MySQL5.7. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
JSON basic operations of MySQL5.7
MySQL has supported JSON format data since version 5.7, and the operation is very convenient.
Creating a table
When creating a new table, the field type can be directly set to the json type. For example, if we create a table:
mysql> CREATE TABLE `test_user`(`id` INT PRIMARY KEY AUTO_INCREMENT, `name` VARCHAR(50) NOT NULL, `info` JSON);
json type field can be NULL
Insert data:
mysql> INSERT INTO test_user(`name`, `info`) VALUES('xiaoming','{"sex": 1, "age": 18, "nick_name": "小萌"}');
The field of json type must be a valid json string
You can use the JSON_OBJECT() function to construct a json object:
mysql> INSERT INTO test_user(`name`, `info`) VALUES('xiaohua', JSON_OBJECT("sex", 0, "age", 17));
Use the JSON_ARRAY() function Construct a json array:
mysql> INSERT INTO test_user(`name`, `info`) VALUES('xiaozhang', JSON_OBJECT("sex", 1, "age", 19, "tag", JSON_ARRAY(3,5,90)));
Now view the data in the test_user table:
mysql> select * from test_user;
+----+-----------+--------------------------------------------+
| id | name | info |
+----+-----------+--------------------------------------------+
| 1 | xiaoming | {"age": 18, "sex": 1, "nick_name": "小萌"} |
| 2 | xiaohua | {"age": 17, "sex": 0} |
| 3 | xiaozhang | {"age": 19, "sex": 1, "tag": [3, 5, 90]} |
+----+-----------+--------------------------------------------+
3 rows in set (0.04 sec)
Query
Expression: The object is a json column->'$.key ', the array is json column->'$.key[index]'
mysql> select name, info->'$.nick_name', info->'$.sex', info->'$.tag[0]' from test_user; +-----------+---------------------+---------------+------------------+ | name | info->'$.nick_name' | info->'$.sex' | info->'$.tag[0]' | +-----------+---------------------+---------------+------------------+ | xiaoming | "小萌" | 1 | NULL | | xiaohua | NULL | 0 | NULL | | xiaozhang | NULL | 1 | 3 | +-----------+---------------------+---------------+------------------+ 3 rows in set (0.04 sec)
is equivalent to: the object is JSON_EXTRACT(json column, '$.key'), the array is JSON_EXTRACT(json column, ' $.key[index]')
mysql> select name, JSON_EXTRACT(info, '$.nick_name'), JSON_EXTRACT(info, '$.sex'), JSON_EXTRACT(info, '$.tag[0]') from test_user; +-----------+-----------------------------------+-----------------------------+--------------------------------+ | name | JSON_EXTRACT(info, '$.nick_name') | JSON_EXTRACT(info, '$.sex') | JSON_EXTRACT(info, '$.tag[0]') | +-----------+-----------------------------------+-----------------------------+--------------------------------+ | xiaoming | "小萌" | 1 | NULL | | xiaohua | NULL | 0 | NULL | | xiaozhang | NULL | 1 | 3 | +-----------+-----------------------------------+-----------------------------+--------------------------------+ 3 rows in set (0.04 sec)
However, I saw that "Xiaomeng" above has double quotes. This is not what we want. We can use the JSON_UNQUOTE function to remove the double quotes
mysql> select name, JSON_UNQUOTE(info->'$.nick_name') from test_user where name='xiaoming'; +----------+-----------------------------------+ | name | JSON_UNQUOTE(info->'$.nick_name') | +----------+-----------------------------------+ | xiaoming | 小萌 | +----------+-----------------------------------+ 1 row in set (0.05 sec)
You can also use the operator directly ->>
mysql> select name, info->>'$.nick_name' from test_user where name='xiaoming'; +----------+----------------------+ | name | info->>'$.nick_name' | +----------+----------------------+ | xiaoming | 小萌 | +----------+----------------------+ 1 row in set (0.06 sec)
Of course attributes can also be used as query conditions
mysql> select name, info->>'$.nick_name' from test_user where info->'$.nick_name'='小萌'; +----------+----------------------+ | name | info->>'$.nick_name' | +----------+----------------------+ | xiaoming | 小萌 | +----------+----------------------+ 1 row in set (0.05 sec)
It is worth mentioning that you can use virtual columns to Quickly query specified attributes of JSON type.
Create virtual columns:
mysql> ALTER TABLE `test_user` ADD `nick_name` VARCHAR(50) GENERATED ALWAYS AS (info->>'$.nick_name') VIRTUAL;
Note that using the operator ->>
is the same as the normal column query:
mysql> select name,nick_name from test_user where nick_name='小萌'; +----------+-----------+ | name | nick_name | +----------+-----------+ | xiaoming | 小萌 | +----------+-----------+ 1 row in set (0.05 sec)
Update
Use JSON_INSERT() to insert new values, but will not overwrite existing values
mysql> UPDATE test_user SET info = JSON_INSERT(info, '$.sex', 1, '$.nick_name', '小花') where id=2;
Look at the results
mysql> select * from test_user where id=2;
+----+---------+--------------------------------------------+-----------+
| id | name | info | nick_name |
+----+---------+--------------------------------------------+-----------+
| 2 | xiaohua | {"age": 17, "sex": 0, "nick_name": "小花"} | 小花 |
+----+---------+--------------------------------------------+-----------+
1 row in set (0.06 sec)
Use JSON_SET() to insert new values and overwrite existing values
mysql> UPDATE test_user SET info = JSON_INSERT(info, '$.sex', 0, '$.nick_name', '小张') where id=3;
Look at the results
mysql> select * from test_user where id=3;
+----+-----------+---------------------------------------------------------------+-----------+
| id | name | info | nick_name |
+----+-----------+---------------------------------------------------------------+-----------+
| 3 | xiaozhang | {"age": 19, "sex": 1, "tag": [3, 5, 90], "nick_name": "小张"} | 小张 |
+----+-----------+---------------------------------------------------------------+-----------+
1 row in set (0.06 sec)
Use JSON_REPLACE() to only replace existing values Value
mysql> UPDATE test_user SET info = JSON_REPLACE(info, '$.sex', 1, '$.tag', '[1,2,3]') where id=2;
Look at the result
mysql> select * from test_user where id=2;
+----+---------+--------------------------------------------+-----------+
| id | name | info | nick_name |
+----+---------+--------------------------------------------+-----------+
| 2 | xiaohua | {"age": 17, "sex": 1, "nick_name": "小花"} | 小花 |
+----+---------+--------------------------------------------+-----------+
1 row in set (0.06 sec)
You can see that the tag is not updated
Delete
Use JSON_REMOVE() to delete JSON elements
mysql> UPDATE test_user SET info = JSON_REMOVE(info, '$.sex', '$.tag') where id=1;
Look at the results
mysql> select * from test_user where id=1;
+----+----------+----------------------------------+-----------+
| id | name | info | nick_name |
+----+----------+----------------------------------+-----------+
| 1 | xiaoming | {"age": 18, "nick_name": "小萌"} | 小萌 |
+----+----------+----------------------------------+-----------+
1 row in set (0.05 sec)
This article is all over here. For more other exciting content, you can follow PHP Chinese Net's MySQL tutorial video column!
The above is the detailed content of Basic JSON operations for MySQL5.7 (code example). For more information, please follow other related articles on the PHP Chinese website!
Securing MySQL Default Installations and ConfigurationsJul 24, 2025 am 02:06 AMModifying the default root password, deleting anonymous users, banning remote root login, removing test databases, and restricting access ports are key steps in MySQL security hardening. First, use the ALTERUSER command to set a strong password and avoid using the root account to connect to the application; secondly, delete anonymous users'@'localhost' and ''@'your_hostname' through DROPUSER; then check and delete the 'root'@'%' account that allows remote login, or create a restricted dedicated account instead; then delete unnecessary test databases and other irrelevant data; finally restrict port 3306 access through firewall tools, or set bind-addres in the configuration file
Understanding MySQL Indexes for WHERE, ORDER BY, GROUP BYJul 24, 2025 am 02:05 AMMySQL indexes are not as fast as possible, and they need to be used reasonably according to the query scenario. 1. The WHERE condition medium value query (=) has the best effect. The range query must comply with the principle of leftmost prefix. Fuzzy match LIKE'abc%' can be indexed, LIKE'�c' is not available, and functions or expressions are avoided in the condition. 2. ORDERBY needs to use indexes to avoid file sorting. It requires that the sorting columns have indexes and the WHERE and ORDERBY columns are in the same order to form a joint index, but range query may cause the sorting to be invalid. 3. GROUPBY recommends using an existing index structure, which prioritizes indexes covering equivalent conditions. Discontinuous columns or inappropriate order will add additional overhead. In addition, the EXPLAIN tool should be paid attention to the implementation plan
Troubleshooting MySQL Replication Sync IssuesJul 24, 2025 am 02:03 AMCommon solutions to the MySQL master-slave synchronization problem are as follows: 1. Check whether the master-slave connection is normal, check the error information of the Last_IO_Error and Last_SQL_Error fields to ensure that the main library port is open and the slave library account has REPLICATIONSLAVE permission; 2. Check whether there are SQL execution errors, if the table does not exist or the field type does not match, skip the error and continue synchronization if necessary; 3. Fix data inconsistency, resynchronize full amount through mysqldump or PerconaXtraBackup, or use pt-table-checksum to detect and repair differences; 4. Optimize configuration and adjust sync_binlog and slave_parall
Choosing the Right MySQL Storage Engine: InnoDB vs MyISAM RevisitedJul 24, 2025 am 02:02 AMInnoDB is suitable for scenarios where transactions, foreign keys, and row-level locks are required. 2. MyISAM is suitable for scenarios where more reads, less writes, and 3. Modern MySQL recommends using InnoDB by default. InnoDB supports transaction processing, crash recovery, foreign key constraints and row-level locking, and is suitable for scenarios with high data consistency requirements such as financial transactions and order processing, with good concurrency performance and high reliability; MyISAM is simple in design and fast query speed, suitable for scenarios where reading operations are mainly based on log statistics and report analysis, but write operations will lock the entire table, affecting concurrency performance; Since MySQL5.5, InnoDB has become the default engine, and continues to obtain new functions and is more applicable. Unless there are special needs, it is recommended to choose InnoDB to avoid late migration costs.
Troubleshooting MySQL Replication User PrivilegesJul 24, 2025 am 01:58 AMMySQL master-slave replication issues are usually caused by improper configuration of replication user rights. 1. Make sure that the replica user has REPLICATIONSLAVE permissions, which can be checked through SHOWGRANTS and added with the GRANT command; 2. Avoid over-authorization and only grant necessary permissions such as REPLICATIONSLAVE and REPLICATIONCLIENT; 3. Check whether the permissions are effective, confirm that there are no spelling errors, FLUSHPRIVILEGES has been executed, the database modification is correct, and MySQL restart is restarted; 4. If the error "Accessdeniedforuser" is reported, the user name and password host should be confirmed, the user existence, firewall and port connectivity should be confirmed.
Optimizing MySQL for Social Media PlatformsJul 24, 2025 am 01:56 AMTooptimizeMySQLforsocialmediaplatforms,startwithindexingstrategies,schemadesign,queryoptimization,andconnectionhandling.1)Usecompositeandcoveringindexeswiselytospeedupquerieswithoutslowingdownwrites.2)Normalizecoredataforconsistencyanddenormalizesele
Optimizing MySQL for Gaming Leaderboards and Player StatsJul 24, 2025 am 01:44 AMTooptimizeMySQLforgamingleaderboardsandplayerstats,useproperdatatypesandindexing,optimizequerieswithwindowfunctions,implementcaching,andconsiderpartitioningorshardingatscale.First,useINTorBIGINTforscoresandDECIMALforfractionalvalues,andapplycompoundi
Securing MySQL Administrative Interfaces and ToolsJul 24, 2025 am 01:41 AMTo avoid exposing the management interface to the public network, it should be accessed through SSH tunnels or intranets; 2. Use a dedicated account and strictly control permissions, disable root remote login; 3. Enable SSL encryption transmission, set strong password policies and cookie authentication; 4. Regularly update the MySQL version and monitor log audit operations. If the MySQL management interface is not protected properly, it should restrict access methods, strengthen authentication, encrypt communications and continuously monitor security status.


Hot AI Tools

Undress AI Tool
Undress images for free

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

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

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

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

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SublimeText3 Linux new version
SublimeText3 Linux latest version

Zend Studio 13.0.1
Powerful PHP integrated development environment







