当前位置:网站首页>mysql json

mysql json

2022-06-23 04:45:00 Jingling cat

Yes mysql Medium json Field Conduct Operate or filter

Official documents mysql JSON Functions

https://dev.mysql.com/doc/refman/5.7/en/json-search-functions.html

JSON Introduction to data types

mysql5.7 above Provides a New field format json, Probably mysql Want to put Non relational and relational databases eat all at once , So this very easy-to-use format is introduced , such , Many of our are based on mongoDb perhaps clickHouse Business... Can be used mysql To achieve . Yes, of course ,5.7 The version of is just the most basic version , The efficiency of massive data is far from enough , But these are mysql8.0 It's solved

JSON  Value will   No longer stored as a string  , It's a kind of   Allow fast reading   Text elements (document elements) Internal binary (internal binary) Format ;
 stay  JSON  Column   Insert or update   Will be   Automatic verification  JSON  Text , Text that fails validation will produce an error message ;
JSON  Text is created in a standard way , have access to   Most comparison operators perform comparison operations  , for example :=, <, <=, >, >=, <>, !=  etc. 

Official website api

 Insert picture description here

Use

-> and ->>

 Insert picture description here
-> stay field When used in, the result is quoted ,->> The result is not quoted

'$' refer to info Field itself , You can also specify which item 

 Insert picture description here
 Insert picture description here

Be careful :-> treat as where Inquire about Yes. Pay attention to the type Of ,->> yes Don't pay attention to the type Of

 It should be noted that , stay  MySQL5.7.17  After the version ,JSON  The element search in is strictly variable type specific 
 For example, integers and strings are strictly distinguished ( Use  ->  In the process of ), But if  ->>  If it is in the form of 

 Notice in the picture below  sql  final  18  quotes 
--  We can find out 
SELECT * FROM `demo` WHERE `info`->'$.age' = 18;

--  I can't find it 
SELECT * FROM `demo` WHERE `info`->'$.age' = '18';

--  We can find out 
SELECT * FROM `demo` WHERE `info`->>'$.age' = 18;

--  We can find out 
SELECT * FROM `demo` WHERE `info`->>'$.age' = '18';

stay order Use in There's no difference

select * from member order by info->"$.id" desc;
select * from member order by info->>"$.id" desc;

establish JSON Field

JSON type It can be for null or not null But there can be no default value

CREATE TABLE `demo` (
	`id` INT(4) NOT NULL AUTO_INCREMENT,
	`info` JSON NOT NULL,
	PRIMARY KEY (`id`)
)ENGINE=INNODB DEFAULT CHARSET=utf8mb4;

Insert JSON data

INSERT INTO test_user(`name`, `info`) VALUES('xiaoming','{"sex": 1, "age": 18, "nick_name": " Xiaomeng "}');

json A field of type must be a Effective json character string
have access to JSON_OBJECT() function structure json object

INSERT INTO test_user(`name`, `info`) VALUES('xiaohua', JSON_OBJECT("sex", 0, "age", 17));

Use JSON_ARRAY() function structure json Array

INSERT INTO test_user(`name`, `info`) VALUES('xiaozhang', JSON_OBJECT("sex", 1, "age", 19, "tag", JSON_ARRAY(3,5,90)));

Look at the data in the table

mysql> select * from test_user; 
+----+-----------+--------------------------------------------+ 
| id | name      | info                                       |
+----+-----------+--------------------------------------------+ 
|  1 | xiaoming  | {
   "age": 18, "sex": 1, "nick_name": " Xiaomeng "} | 
|  2 | xiaohua   | {
   "age": 17, "sex": 0}                      |
|  3 | xiaozhang | {
   "age": 19, "sex": 1, "tag": [3, 5, 90]}   | 
+----+-----------+--------------------------------------------+
3 rows in set (0.04 sec)

Inquire about

json_extract( Field name ,$.json Field name ) Inquire about json A property in / list

Query expression : object by json Column -> '$. key ', Array by 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  | " Xiaomeng "              | 1             | NULL             | 
| xiaohua   | NULL                | 0             | NULL             | 
| xiaozhang | NULL                | 1             | 3                | 
+-----------+---------------------+---------------+------------------+ 
3 rows in set (0.04 sec)

Query expression : object by JSON_EXTRACT(json Column , '$. key '), Array by 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  | " Xiaomeng "                            | 1                           | NULL                           |
| xiaohua   | NULL                              | 0                           | NULL                           | 
| xiaozhang | NULL                              | 1                           | 3                              | 
+-----------+-----------------------------------+-----------------------------+--------------------------------+ 
3 rows in set (0.04 sec)

JSON_CONTAINS():JSON Whether the format data contains a specific object in the field

JSON_CONTAINS(target, candidate[, path])

 Want to query the contents  deptName= department 5  The object of 

select * from dept WHERE JSON_CONTAINS(json_value, JSON_OBJECT("deptName"," department 5"))

Remove double quotes

See above " Xiaomeng " It's in double quotation marks , This is not what we want , It can be used JSON_UNQUOTE function Remove the double quotation marks

mysql> select name, JSON_UNQUOTE(info->'$.nick_name') from test_user where name='xiaoming'; 
+----------+-----------------------------------+ 
| name     | JSON_UNQUOTE(info->'$.nick_name') | 
+----------+-----------------------------------+ 
| xiaoming |  Xiaomeng                               | 
+----------+-----------------------------------+ 
1 row in set (0.05 sec)

perhaps Use operators directly ->>

mysql> select name, info->>'$.nick_name' from test_user where name='xiaoming';
+----------+----------------------+ 
| name     | info->>'$.nick_name' | 
+----------+----------------------+ 
| xiaoming |  Xiaomeng                  | 
+----------+----------------------+ 
1 row in set (0.06 sec)

 Of course, it can also be used as a query condition 
mysql> select name, info->>'$.nick_name' from test_user where info->'$.nick_name'=' Xiaomeng '; 
+----------+----------------------+ 
| name     | info->>'$.nick_name' | 
+----------+----------------------+ 
| xiaoming |  Xiaomeng                  | 
+----------+----------------------+ 
1 row in set (0.05 sec)

Fast query through virtual columns

adopt Virtual column Yes JSON The specified attribute of the type Make a quick query

 Create virtual columns 
mysql> ALTER TABLE `test_user` ADD `nick_name` VARCHAR(50) GENERATED ALWAYS AS (info->>'$.nick_name') VIRTUAL;

 Note the operator ->>
 When used, it is the same as the ordinary type of column query 

mysql> select name,nick_name from test_user where nick_name=' Xiaomeng '; 
+----------+-----------+ 
| name     | nick_name | 
+----------+-----------+ 
| xiaoming |  Xiaomeng       | 
+----------+-----------+ 
1 row in set (0.05 sec)

JSON Query as a condition

JSON It's not like a normal string , If Directly combine the string with JSON Field to compare , No results will be found

--  No data to query 
SELECT * FROM `demo` WHERE `info` = '{"age": 18, "name": "andy"}';

Use CAST function Convert string to JSON In the form of

SELECT * FROM `demo` WHERE `info` = CAST('{"age": 18, "name": "andy"}' AS JSON);

JSON The elements in the data are queried as conditions

Appoint JSON The method of element is :column -> '$.path' or column -> '$[index]'

SELECT * FROM `demo` WHERE `info`->'$.name' = 'andy';
 As mentioned above  column->path  The query string contains double quotation marks 
 and  column->>path  No double quotes , But when querying as a condition ,->  and  ->>  The query results are the same, including double quotation marks 

JSON_TYPE(): Query a json Field attribute type

 Would you like to inquire deptName What are the field properties of 

SELECT json_value->'$.deptName' ,JSON_TYPE(json_value->'$.deptName') as type from dept 

 Insert picture description here

json_valid : Is it effective json

select json_valid(id),json_valid(info) from member;

 Insert picture description here

JSON_KEYS() :JSON Key array in document

 Would you like to inquire json All in the format data key

SELECT JSON_KEYS(json_value) FROM dept 

 Insert picture description here

json_depth and json_length

 Insert picture description here

select json_depth(info) from member;
json yes   An empty array   perhaps   An empty object   Yes, the return is 1

 Insert picture description here

select json_length(info) from member;

 Insert picture description here

Update data

Update the whole JSON

UPDATE `demo` SET `info` = '{"name": "joe", "age": 15}' WHERE `id` = 3;

JSON_INSERT

Insert new element value , but Does not overwrite existing element values

--  Only new sex nick_name Elements , Will not cover age Elements 
mysql> UPDATE test_user SET info = JSON_INSERT(info, '$.sex', 1, '$.nick_name', ' floret ') where id=2;

mysql> select * from test_user where id=2; 
+----+---------+--------------------------------------------+-----------+ 
| id | name    | info                                       | nick_name | 
+----+---------+--------------------------------------------+-----------+ 
|  2 | xiaohua | {
   "age": 17, "sex": 0, "nick_name": " floret "} |  floret       | 
+----+---------+--------------------------------------------+-----------+ 
1 row in set (0.06 sec)

JSON_SET

Set the value , If If the element does not exist, create , If If it already exists, overwrite the old value

mysql> UPDATE test_user SET info = JSON_INSERT(info, '$.sex', 0, '$.nick_name', ' Xiao Zhang ') where id=3;

mysql> select * from test_user where id=3; 
+----+-----------+---------------------------------------------------------------+-----------+ 
| id | name      | info                                                          | nick_name | 
+----+-----------+---------------------------------------------------------------+-----------+ 
|  3 | xiaozhang | {
   "age": 19, "sex": 0, "tag": [3, 5, 90], "nick_name": " Xiao Zhang "} |  Xiao Zhang       | 
+----+-----------+---------------------------------------------------------------+-----------+ 
1 row in set (0.06 sec)

JSON_REPLACE

It's just Replace existing element values

mysql> UPDATE test_user SET info = JSON_REPLACE(info, '$.sex', 1, '$.tag', '[1,2,3]') where id=2;

mysql> select * from test_user where id=2; 
+----+---------+--------------------------------------------+-----------+ 
| id | name    | info                                       | nick_name | 
+----+---------+--------------------------------------------+-----------+ 
|  2 | xiaohua | {
   "age": 17, "sex": 1, "nick_name": " floret "} |  floret       | 
+----+---------+--------------------------------------------+-----------+ 
1 row in set (0.06 sec)

tag Not updated 

JSON_REMOVE

Delete JSON Elements

mysql> UPDATE test_user SET info = JSON_REMOVE(info, '$.sex', '$.tag') where id=1;

mysql> select * from test_user where id=1; 
+----+----------+----------------------------------+-----------+ 
| id | name     | info                             | nick_name | 
+----+----------+----------------------------------+-----------+ 
|  1 | xiaoming | {
   "age": 18, "nick_name": " Xiaomeng "} |  Xiaomeng       | 
+----+----------+----------------------------------+-----------+ 
1 row in set (0.05 sec)

json_array_append

 Insert picture description here
Append a value to the specified location

select json_array_append(info, '$', 1) from member;
'$' refer to info Field itself , You can also specify which item 

 Insert picture description here

select json_array_append(info, '$[1]', 2) from member;

 Subscript cannot be negative , Will report a mistake , No more than the original json Number , Will be ignored 

 Insert picture description here

JSON_ARRAY_INSERT

Inserts a value before the specified position

// UPDATE `demo` SET `info` = JSON_ARRAY_INSERT(`info`, '$[1]', 0) WHERE `id` = 2;

select json_array_insert(info, '$[1]', 100) from member;

 The subscript cannot also be negative , But it can exceed json Number , To exceed is to insert to the end 

 Insert picture description here

原网站

版权声明
本文为[Jingling cat]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/174/202206230008410234.html