当前位置:网站首页>MySQL stores JSON format data
MySQL stores JSON format data
2022-07-29 02:10:00 【xiaoweiwei99】
Mysql5.7 New features after version ,Mysql Provides a native Json type ,Json Values will no longer be stored as strings , Instead, it uses a method that allows fast reading of text elements (document elements) Internal binary (internal binary) Format . stay Json When the column is inserted or updated, it will be automatically verified Json Text , Text that fails validation will produce an error message
JSON The data type is recommended for static data storage that is not updated frequently
Create table t_user
CREATE TABLE `t_user_tag` (
`id` int NOT NULL AUTO_INCREMENT,
`tag_name` varchar(255) COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT ' Tag name ',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

The login method field uses json Format , It is divided into phone,wechat,qq,email,zhifubao wait
insert data :
insert into t_user values (1,'tom', 25, '{"email": "[email protected]", "phone": "13200001111", "wechat": "147258369"}');
insert into t_user values (2,'jack', 30, '{"phone": "13500001111"}');
insert into t_user values (3,'lily', 18, '{"qq": "147258369", "phone": "13600001111"}');
insert into t_user values (4,'lily', 45, '{"wechat":"1884875663"}');

Inquire about
user name , cell-phone number , WeChat ID
select name,
(JSON_EXTRACT(login_info, '$.phone')) phone,
JSON_UNQUOTE(JSON_EXTRACT(login_info, '$.wechat')) wechat
from t_user;

It can be seen that
JSON_UNQUOTE The function is to Remove json Quotes for Strings , Convert the value to string type
JSON_EXTRACT The function is to extract json value
The concise writing is equivalent to the above
select name,
login_info ->> '$.phone' phone,
login_info ->> '$.wechat' wechat
from t_user;

->> expression Equate to JSON_UNQUOTE(JSON_EXTRACT(login_info, ‘$.wechat’))
-- Use json The fields in are used as query criteria
select name,
login_info ->> '$.phone' phone,
login_info ->> '$.wechat' wechat
from t_user
where login_info ->> '$.phone' = '13200001111';

json data Add index
to login_info Add an index to the mobile number in the field
-- to login_info This json Medium phone Add index
alter table t_user add COLUMN phone varchar(11) as (login_info ->> '$.phone');
alter table t_user add UNIQUE INDEX idx_uq_phone(phone);
Above SQL First, create a virtual column phone, This column is made up of functions login_info->>“$.phone” Calculated . Then create a unique index on this virtual column idx_uq_phone. At this time, through the virtual column phone The query , You can see that the optimizer will use the newly created idx_uq_phone Indexes
-- Look at the index
EXPLAIN
select *
from t_user
where phone = '13200001111';

Let's look at the table structure , I found that the index was increased

Use scenarios
Some businesses need user portraits ( That is to label users ), Then according to the user's label , Through data mining technology , Make corresponding product recommendations . such as :
In the e-commerce industry , According to the user's dressing preferences , Recommend corresponding products ;
In the music industry , According to the music style users like and the singers they often listen to , Recommend the corresponding song ;
In the financial industry , According to the user's risk preference and investment experience , Recommend corresponding financial products .
Here , I strongly recommend that you use JSON Type stores user portrait information in the database , And combine JSON The characteristics of array type and multivalued index are used for efficient query .
Create a user portrait definition table :
CREATE TABLE `t_tag` (
`id` int NOT NULL AUTO_INCREMENT,
`tag_name` varchar(255) COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT ' Tag name ',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

insert into t_tag values (null, '70 after ');
insert into t_tag values (null, '80 after ');
insert into t_tag values (null, '90 after ');
insert into t_tag values (null, '00 after ');
insert into t_tag values (null, '10 after ');
insert into t_tag values (null, ' Love sports ');
insert into t_tag values (null, ' Love listening to music ');
insert into t_tag values (null, ' I love watching movies ');
insert into t_tag values (null, ' Highly educated ');
insert into t_tag values (null, ' Small endowment ');
insert into t_tag values (null, ' A car ');
insert into t_tag values (null, ' There are children ');
insert into t_tag values (null, ' I like online shopping ');
insert into t_tag values (null, ' Like some takeout ');
insert into t_tag values (null, ' lolita ');
Create user label middle table
CREATE TABLE `t_user_tag` (
`user_id` int NOT NULL COMMENT ' user id',
`tag_id` json NOT NULL COMMENT ' User label id',
PRIMARY KEY (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

insert data , Use an array to store
insert into t_user_tag values (1,'[2,4,6]');
insert into t_user_tag values (2,'[1,3,7]');
insert into t_user_tag values (3,'[8,10,12]');

MySQL 8.0.17 Version starting support Multi-Valued Indexes, Used in JSON Create index on array , And through the function member of、json_contains、json_overlaps To quickly retrieve index data . So you can watch UserTag To create a Multi-Valued Indexes:
ALTER TABLE t_user_tag
ADD INDEX idx_user_tags ((cast((tag_id->"$") as unsigned array)));

Inquire about those who love watching movies

select * from t_user_tag
where 8 MEMBER OF(tag_id -> '$');

I love watching movies , With children
select * from t_user_tag
where JSON_CONTAINS(tag_id -> '$', '[8,10]');

Use JSON data type , Recommend to use MySQL 8.0.17 Version above , Better performance , It also supports Multi-Valued Indexes;
JSON The advantage of data types is that there is no need to define columns in advance , The data itself is well descriptive ;
Don't use data with obvious relationship JSON Storage , Such as user balance 、 User name 、 User ID card, etc , These are the data that every user must include ;
JSON The data type is recommended for static data storage that is not updated frequently .
边栏推荐
- Explanation of yocto project directory structure
- Mathematical modeling - location of police stations
- Process -- user address space and kernel address space
- 在Qt中如何编写插件,加载插件和卸载插件
- Comprehensive use method of C treeview control
- How to crawl web pages with playwright?
- (arxiv-2018) reexamine the time modeling of person Reid based on video
- Form verification hidden input box is displayed before verification
- How to prevent all kinds of affiliated fraud?
- Try to understand the essence of low code platform design from another angle
猜你喜欢

Mobile communication -- simulation model of error control system based on convolutional code

Add graceful annotations to latex formula; "Data science" interview questions collection of RI Gai; College Students' computer self-study guide; Personal firewall; Cutting edge materials / papers | sh

LeetCode 练习——剑指 Offer 45. 把数组排成最小的数

FPGA实现10M多功能信号发生器

Js DOM2 和 DOM3

druid. IO custom real-time task scheduling policy

Mathematical modeling -- heat conduction of subgrade on Permafrost
[electronic components] zener diode

基于C51控制蜂鸣器

ciscn 2022 华中赛区 misc
随机推荐
在Qt中如何编写插件,加载插件和卸载插件
druid. io kill -9 index_ Realtime traceability task
Lm13 morphological quantification momentum period analysis
【ONE·Data || 链式二叉树】
Mobile communication -- simulation model of error control system based on convolutional code
Add graceful annotations to latex formula; "Data science" interview questions collection of RI Gai; College Students' computer self-study guide; Personal firewall; Cutting edge materials / papers | sh
Mathematical modeling -- cold proof simulation of low temperature protective clothing with phase change materials
【流放之路-第三章】
Probability Density Reweight
Comprehensive analysis of news capture doorway
移动通信——基于卷积码的差错控制系统仿真模型
Explanation of yocto project directory structure
The growth path of embedded engineers
[circuit design] convert AC AC to DC
Ignore wechat font settings
12.< tag-动态规划和子序列, 子数组>lt.72. 编辑距离
[electronic components] constant voltage, amplify the current of the load (triode knowledge summary)
[the road of Exile - Chapter 8]
[MySQL] SQL aliases the table
Lua log implementation -- print table