Query fields in json format in MySQL

There is a requirement during the work development process: the customer’s name, mobile phone number, ID card, and certificate type need to be dynamically stored, which means that the front-end may transmit the information of one person or two or three people. There are four fields with dynamic and variable numbers of people. (Name, mobile phone number, ID card, certificate type).

The front-end page is as follows:
This is the front-end image
I am using List来接收前端传过来 json,mysql 用 varchar 来保存这个 json 数组

[{
    
    
	"cardId": "110101199003072316",
	"cstName": "张双儿1",
	"cstMobile": "13263654144",
	"idCardType": "1"
}, {
    
    
	"cardId": "11010119900307571X",
	"cstName": "张双儿2",
	"cstMobile": "13263654144",
	"idCardType": "1"
}]

The product's requirement is to vaguely query the information of these joint customers. At first, I wrote the wrong way:
select * from signCustomerGroup like'%儿%'
but later found that there was a problem, such as vaguely inputting a letter c, it would put the left'cardId' 'Matches the English field name.
Later, I learned that the json type was added to MySQL 5.7 and later versions. You can use some functions of the json type to directly query a field in the json format.

The correct syntax is as follows:
Table field:

id sign_customer_info_ext
1 [{“CstName”: “hhjk”, “cstMobile”: “14258669888”, “idCardType”: “1”, “cardId”: “460101199601012516”}]
2 [{“CstName”: “ghhj 中文 1355”, “cstMobile”: “18253558608”, “idCardType”: “1”, “cardId”: “460101199601012815”}, {“cstName”: “fhjj 重要 133366”, “cstMobile ”:“ 15555555555 ”,“ idCardType ”:“ 1 ”,“ cardId ”:“ 460101199601012313 ”}]

Insert picture description here

The main SQL function used is json_extract(), its function is to find all specified data from JSON format

1. json array query

模糊查询 json 数组格式的字段中某个字段:
使用方式:
SELECT * FROM 表名 WHERE json_extract(字段名,"$[*].json中key") like '%需要搜索的值%';
实例:
SELECT * FROM table WHERE json_extract(sign_customer_info_ext,"$[*].cstName") like '%h%';
精准查询(注意:精准查询必须写明所查询字段所属数组那个下标,比如查排在一个就是 [0],第二个就是 [1])
SELECT id,sign_customer_info_ext FROM table WHERE json_extract(sign_customer_info_ext,"$[0].cstName") = 'ghhj中文1355';

2. Single json query
Single json parameter in front-end and mysql database:

{
	"cstName": "马云",
	"cstMobile": "17879767646",
	"idCardType": "1",
	"cardId": "E4813980"
}
模糊查询单个 json 查询:
使用方式:
SELECT id,sign_customer_info_ext FROM 表名 WHERE json_extract(字段名,"$.json中key") like '%马云%';
实例:
SELECT id,sign_customer_info_ext FROM table  WHERE json_extract(sign_customer_info_ext,"$.cstName") like '%马云%';

Guess you like

Origin blog.csdn.net/weixin_46756314/article/details/112286652