PostgreSQL Json字段作为查询条件的解决方案
读前思考:
你没想到解决办法?PostgreSQL 数据库本身就支持还是另有解决办法?
使用JOSNB作为字段类型。现在开始,,,,,,,,,,,,,,,,,,
json如下:
"rule":{ "tags": { "target": "logon" }, "time": "2019-11-15 10:00:00", "method": "scheduled", "source": "backend", "aliases": [], "sendType": "tag", "registrationIds": [] }
现在我想获取 rule 字段 里面的 sendType="tag",那现在怎么搞?
代码如下:
#####Mybatis##### <select id="selectPushDataList" resultMap="BaseResultMap" parameterType="com.jpc.JpushData" > SELECT <include refid="Base_Column_List" /> FROM jp_push jpt <where> delete_flag=1 and (rule::json->>'sendType')::text = 'tag' <if test="name != null and name !=''" > and name =#{name,jdbcType=VARCHAR} </if> ORDER BY create_time ASC LIMIT ${pageSize} OFFSET ${(currentPage - 1) * pageSize} </where> </select> ####PostgreSQL SQL#### SELECT uuid,create_user,create_time,update_user,update_time,delete_flag,NAME,type,push,rule, STATUS FROM jp_push jpt WHERE jpt.delete_flag = 1 AND ( jpct.rule :: json ->> 'sendType' ) :: text = 'tag' AND jpt.NAME = 'testname' ORDER BY jpt.create_time ASC LIMIT 20 OFFSET 0
结果如下:
再看如下的json串:
--如何获取title,description呢--------
----------pre- zh en app----------
"pre": {
"zh": {
"app": {
"title": "test",
"description": "test",
"images": [
"https://www.baidu.com/",
"https://www.baidu.com/1"
]
}
},
"en": {
"app": {
"title": "test",
"description": "test",
"images": [
"https://www.baidu.com/",
"https://www.baidu.com/1"
]
}
}
---------------pre zh en web------------------------------------
"pre": {
"zh": {
"web": {
"title": "test",
"description": "test",
"images": [
"https://www.baidu.com/",
"https://www.baidu.com/1"
]
}
},
"en": {
"web": {
"title": "test",
"description": "test",
"images": [
"https://www.baidu.com/",
"https://www.baidu.com/1"
]
}
}
}
如何写sql? 把语言和端作为一个变量传进去...
SELECT uuid, address,pre, pre :: json -> '${lunguage}' -> '${device}' ->> 'title' AS title, pre :: json -> '${lunguage}' -> '${device}' ->> 'description' AS description FROM "ban".test j
获取 zh-web不为空的内容:
lunguage 传 zh,device传 web
SELECT uuid,address, pre, pre :: json -> '${lunguage}' -> '${device}' ->> 'title' AS title, pre :: json -> '${lunguage}' -> '${device}' ->> 'description' AS description FROM "ban".test j where pre :: json -> '${lunguage}' -> '${device}' is not null
获取 zh-web-images数组里面的第一个图片信息不为空的内容:
SELECT
uuid,address, pre, pre :: json -> '${lunguage}' -> '${device}' ->> 'title' AS title, pre :: json -> '${lunguage}' -> '${device}' ->> 'description' AS description, pre :: json -> '${lunguage}' -> '${device}' ->>0::'images' AS images FROM
"ban".test j where pre :: json -> '${lunguage}' -> '${device}' is not null
总结:PostgreSQL 本身就支持以json作为sql的查询条件。