当前位置:网站首页>MySQL learning notes: JSON nested array query
MySQL learning notes: JSON nested array query
2022-06-11 03:08:00 【Mountain Ghost ballad me】
Environmental Science
MySQL 5.7
Let's assume that the data
Simple JSON Don't talk about it , It's simple , Make it a little more complicated :
[
{
"type":[
{
"code":"xmf",
"name":" Little bee "
}
],
"cities":[
{
"code":"1",
"name":" Shanghai "
}
],
"oType":[
{
"code":"order",
"name":" list "
}
],
"p":[
{
"code":"110",
"name":" Hurry up "
}
]
}
]
stay MySQL In the database , It looks like this :

The picture above is just for illustration , Whole above JSON The corresponding field of the string in the database is detail.
On the Internet, many are first {......} object , Then nest the array , But my data is [......], namely : First, an array , Then nest the objects , Then nest the array .
In this case , How to query ?
MySQL Nested array query method
Now I want to check ,JSON The city field in the string is Shanghai .
Correct SQL:
SELECT *
from `template_yutao`
where json_contains( `detail`, json_object('cities', json_array(json_object('name', ' Shanghai '))))
Ideas :json_contains effect : Whether to include sub documents . Let's construct a sub document , Then enter it to query .
I have tried to use the extraction method , Want to abbreviate the above SQL:
-- Want to extract first cities This floor , Query again
-- unfortunately , stay json_contains It can't write * or **
SELECT * from `alsc_cs_minos_template_biz`
where json_contains( `detail`, json_object('name', ' Shanghai '), '$[*].cities')
-- Then it was rewritten as The following can be successful , however $[0] The equals limit becomes the first of the array , It is not convenient to expand in the future .
-- Studied for half a day , There is no way to extract one layer ; But the above query is enough .
-- In fact, because json_contains It can't write * or **, It has been shown that it can not be extracted , Only extraction can be specified explicitly .
SELECT * from `alsc_cs_minos_template_biz`
where json_contains( `detail`, json_object('name', ' Shanghai '), '$[0].cities')
explain :
It needs to be said here , above json Inquire about , and MongoDB be similar , But it didn't MongoDB Powerful ,MongoDB Words , Just check it out :
SELECT *
from `template_yutao`
where detail.cities.name = ' Shanghai ' -- This is not standard MongoDB How to write it , Just want to express the general meaning .
-- MongoDB Standard writing
db.template_yutao.find('$.detail.cities.name', ' Shanghai ');
Mybatis combination
Suppose we use Mybatis-Generator Generate Mapper The code in the file is :criteria The form of class .
Mapper.xml Form like :
<if test="_parameter != null">
<where>
<foreach collection="oredCriteria" item="criteria" separator="or">
<if test="criteria.valid">
<trim prefix="(" prefixOverrides="and" suffix=")">
<foreach collection="criteria.criteria" item="criterion">
<choose>
<when test="criterion.noValue">
and ${criterion.condition}
</when>
<when test="criterion.singleValue">
and t.${criterion.condition} #{criterion.value}
</when>
<when test="criterion.betweenValue">
and t.${criterion.condition} #{criterion.value} and #{criterion.secondValue}
</when>
<when test="criterion.listValue">
and t.${criterion.condition}
<foreach close=")" collection="criterion.value" item="listItem" open="(" separator=",">
#{listItem}
</foreach>
</when>
</choose>
</foreach>
</trim>
</if>
</foreach>
</where>
</if>
<if test="orderByClause != null">
order by ${@[email protected](orderByClause)}
</if>
<if test="page">
limit #{pageIndex},#{pageSize}
</if>
Related classes XXXParam class , It's like the following form :
protected abstract static class AbstractGeneratedCriteria {
protected List<Criterion> criteria;
protected AbstractGeneratedCriteria() {
super();
criteria = new ArrayList<Criterion>();
}
public boolean isValid() {
return criteria.size() > 0;
}
public List<Criterion> getAllCriteria() {
return criteria;
}
public List<Criterion> getCriteria() {
return criteria;
}
protected void addCriterion(String condition) {
if (condition == null) {
throw new RuntimeException("Value for condition cannot be null");
}
criteria.add(new Criterion(condition));
}
protected void addCriterion(String condition, Object value, String property) {
if (value == null) {
throw new RuntimeException("Value for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value));
}
protected void addCriterion(String condition, Object value1, Object value2, String property) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value1, value2));
}
public Criteria andIdIsNull() {
addCriterion("id is null");
return (Criteria) this;
}
public Criteria andIdIsNotNull() {
addCriterion("id is not null");
return (Criteria) this;
}
Then at this time , How to write the code ?
My method is to add the following method to it :
/** * * @param cityList * @return */
public Criteria andCityCodeJson(List<String> cityList) {
if (cityList == null || cityList.size() == 0) {
throw new RuntimeException("Value for cityList cannot be null");
}
StringBuilder cityStr = new StringBuilder();
int size = cityList.size();
for (int i = 0; i < size; i++) {
if (i == size - 1) {
cityStr.append("json_object('code', '").append(cityList.get(i)).append("')");
} else {
cityStr.append("json_object('code', '").append(cityList.get(i)).append("')").append(",");
}
}
addCriterion("json_contains(detail, json_object('city', json_array(" + cityStr +")))");
return (Criteria) this;
}
MySQL JSON Method statement
The following is a brief description , Concise and comprehensive , Please refer to the official website for details :
12.18.3 Functions That Search JSON Values
json_contains
JSON_CONTAINS(json_doc, val[, path]) Whether to include sub documents .
JSON_EXTRACT
JSON_EXTRACT(json_doc, path[, path] …) get doc The value of one or more nodes in the .
Reference address
12.18.3 Functions That Search JSON Values
边栏推荐
- Help you distinguish GNU, GCC, GCC and G++
- If you understand the logic of mining and carbon neutrality, you will understand the 100 billion market of driverless mining areas
- com. mchange. v2.c3p0. Combopooleddatasource red
- The new colleague asked me what "where 1=1" means???
- 马志强:语音识别技术研究进展和应用落地分享丨RTC Dev Meetup
- WinDbg-虚拟机-双机调试-驱动文件的调试
- How to handle error code 30204-44 when installing office 2016 in win10?
- File file = new file ("test.txt") file path
- B_QuRT_User_Guide(18)
- Ora-00392 ora-00312 error handling
猜你喜欢

com. mchange. v2.c3p0. Combopooleddatasource red

How to state clearly and concisely the product requirements?
![[big guy show] aiops in the eyes of Borui data, choosing the right track and the right people](/img/a6/61d125326fc81532a56858c384460f.jpg)
[big guy show] aiops in the eyes of Borui data, choosing the right track and the right people

2022年熔化焊接与热切割操作证考试题库及答案

三维GIS行业需求及展望

Go 语言的优势和学习路线图

Wechat applet

Demand and Prospect of 3D GIS Industry

Unity项目优化详解(持续补充ing)

2022年6月中国数据库排行榜:TiDB卷土重来摘桂冠,达梦蛰伏五月夺探花
随机推荐
In June, 2022, China Database ranking: tidb made a comeback to win the crown, and Dameng was dormant and won the flowers in May
Help you distinguish GNU, GCC, GCC and G++
023 MySQL索引优化口诀-索引失效的常见情况
【大咖秀】博睿数据眼中的AIOps,选择正确的赛道正确的人
两部门联合印发《校外培训机构消防安全管理九项规定》
Shell reads files by line
B_QuRT_User_Guide(20)
反射三种方式
Three ways of reflection
Hough transform of image
The two departments jointly issued the nine provisions on fire safety management of off campus training institutions
文件合成器
ROS基础 - 使用 launch 文件(一) - 批量启动多个ROS节点
C语言指针
Rs232/rs485 to 4G DTU uploading temperature and humidity sensor data based on Modbus protocol to remote TCP server
postgresql源码学习(十七)—— MVCC②-快照与隔离级别简介
C language pointer
Hqchart nailing applet tutorial 1- create a K-line diagram
Young people fleeing big cities: shouldering housing prices and pressure, but not epidemics
Stringutils string tool class used by FreeMarker to create templates