sql - 要列出的 SQL 列值搜索文本
问题描述
我想使用 SQL 从日志表中获取状态值作为列表。
响应列:(完整字符串)“
{"headers":{"date":"Wed, 07 Oct 2020 06:46:33 GMT","server":"RR/1.983","transfer-encoding":"chunked","vary":"Accept-Encoding","x-frame-options":"SAMEORIGIN;","access-control-allow-headers":"Content-Type, Authorization","strict-transport-security":"max-age\u003d63072000","access-control-allow-methods":"GET, POST, DELETE, PUT, PATCH, OPTIONS","access-control-allow-origin":"*","access-control-allow-credentials":"true","x-xss-protection":"1; mode\u003dblock","x-content-type-options":"nosniff","content-type":"application/json;charset\u003dutf-8","cache-control":"no-transform"},
"body":[
{"index":114,"status":"success","subRequestId":"0051"}},
{"index":114,"status":"failure","subRequestId":"0052"}},
{"index":114,"status":"failure","subRequestId":"0053"}},
],"status":200}
"
我想得到:
{"index":114,"status":"failure","subRequestId":"0052"}}
{"index":114,"status":"failure","subRequestId":"0053"}}
我试过了:
select log.RESPONSE
from LOG_TABLE log
where log.RESPONSE like ('%failure%');
我怎样才能用sql做到这一点,你能帮忙吗?
解决方案
请指定您的数据库供应商。对于 Postgres,请使用Postgres JSON 函数。
您可以使用此查询(db fiddle)来实现您请求的结果:
with log (response) as (values('{"headers":{},
"body":[
{"index":114,"status":"success","subRequestId":"0051"},
{"index":114,"status":"failure","subRequestId":"0052"},
{"index":114,"status":"failure","subRequestId":"0053"}
],"status":200}'::json)
)
select x.*
from log, json_array_elements(log.response->'body') as x(v)
where x.v->>'status' like '%failure%'
对于更复杂的情况,您可能希望打破内部 json 以设置使用json_to_recordset
,然后将其组装回 json。
指定供应商后更新:然后使用Oracle 函数(db fiddle):
with log (response) as (select '{"headers":{},
"body":[
{"index":114,"status":"success","subRequestId":"0051"},
{"index":114,"status":"failure","subRequestId":"0052"},
{"index":114,"status":"failure","subRequestId":"0053"}
],"status":200}' from dual
)
select json_object('index' value "index",'status' value "status",'subRequestId' value "subRequestId")
from log, json_table(response, '$.body[*]' columns (
"index" number path '$.index',
"status" varchar2(4000) path '$.status',
"subRequestId" varchar2(4000) path '$.subRequestId'
)) x
where x."status" like '%failure%'
或更短的版本相当于上面的 Postgres 方言(db fiddle):
select x.*
from log
, json_table(response, '$.body[*]' columns (
obj varchar2(4000) format json path '$'
)) as x
where json_value(x.obj,'$.status') like '%failure%'
注意自 v.12 起添加了 JSON 支持。
推荐阅读
- java - 用php连接java
- html - 想要更改标题链接 WordPress 上的悬停颜色
- reactjs - 反应原生:试图分配给只读属性
- html - 为什么“显示:无”仍然占用空间?
- java - Spring boot 自定义注释中的方面
- javascript - javascript中是否存在线程不安全的可能性?
- amazon-web-services - AWS Kinesis Firehose 在美国西部,但在美国东部输出 S3 存储桶
- firebase - nuxt (SSR) 和 Firestore 规则的问题
- javascript - 我的 node.js react 应用程序无法识别任何 index.html 文件是否有任何明显的原因?
- objective-c - 检查数组值是否是 Swift 4 中的有效数字