【问题标题】:How to Filter Json Object in Json Array?如何过滤 Json 数组中的 Json 对象?
【发布时间】:2019-05-02 19:01:30
【问题描述】:

我有一些数据存储在 sql 列中,看起来像

{
  "items": [
    { "ids": [4], "fromCompanyId": 4 },
    { "ids": [6, 1], "fromCompanyId": 1 }
  ]
}

现在我想创建一个 where 子句来查找所有“fromCompanyId”为“4”的“项目”。

到目前为止我发现的只是

WHERE JSON_VALUE(jsonInfo,'$.info.address[0].state') LIKE 'US%'

但他们对数组索引进行了硬编码。我需要找到所有匹配项。

我也在尝试 openJson 但仍然无法正常工作

where 4 in (select fromCompanyId  from openjson(Details, '$.items.fromCompanyId') WITH( [fromCompanyId] int '$.fromCompanyId')))

【问题讨论】:

  • 你在一月份没有问过同样的问题吗? stackoverflow.com/questions/54014774/… 使用 OPENJSON 的答案似乎与此相关。
  • 它很相似,但那是一个字符串数组。这是 json 对象数组,当我尝试 openJson 时它不起作用,所以我可能做错了。
  • @JamieD77 - 我查看了该链接,但仍然无法为我工作,所以我可能做错了。我更新了我的 OP。
  • openjson(Details, '$.items') WITH( [fromCompanyId] int '$.fromCompanyId')))

标签: json sql-server sql-server-2017


【解决方案1】:

您需要在多个级别上openjson。像这样的。

declare @json nvarchar(max)=N'{
  "items": [
    { "ids": [4], "fromCompanyId": 4 },
    { "ids": [6, 1], "fromCompanyId": 1 }
  ]
}'

select id,fromCompanyId
from openjson(@json,'$.items') j --path to the main array
cross apply openjson(value,'$.ids') -- path inside element of main array
with(id int '$')
cross apply openjson(value)
with (
fromCompanyId int '$.fromCompanyId'
)
where fromCompanyId=4

与表格字段类似。

declare @tbl table (id int, detail nvarchar(max))
insert @tbl (id,detail) values
(1,N'{
  "items": [
    { "ids": [4], "fromCompanyId": 4 },
    { "ids": [6, 1], "fromCompanyId": 1 }
  ]
}'),
(2,N'{
  "items": [
    { "ids": [5], "fromCompanyId": 4 },
    { "ids": [7,9], "fromCompanyId": 4 },
    { "ids": [6, 1], "fromCompanyId": 1 }
  ]
}')

select id,jid,fromCompanyId
from @tbl
cross apply openjson(detail,'$.items') -- path to the main array
cross apply openjson(value,'$.ids') -- path inside array element
with(jid int '$')
cross apply openjson(value)
with (
fromCompanyId int '$.fromCompanyId'
)
where fromCompanyId=4

【讨论】:

    【解决方案2】:

    SQL 不是此搜索的正确位置。除了这个搜索的性能有多糟糕之外,查询对于 CPU 和 IO 等数据库资源来说将非常昂贵。 随着表中数据的增长,查询将呈指数级增长。 如果实际 JSON 超过 8000char(如果存储为 NVARCHAR,则为 4k),即使没有太多数据增长,它也会被存储在行外,因此每次它必须读取 BLOB。

    我建议只从 db 读取并解析 inn 应用程序端的任何语言。那会更便宜。

    简而言之:这不是 SQL 任务。您应该首先查看工作流程和流程改进。如果搜索查询是常规用户工作流程,则其自身的架构设计可能不适合此工作流程。

    【讨论】:

    • 这可能有道理,但与 OP 无关。 MS SQL Server 仍然没有对json 数据的native 支持(就像对xml 一样),但有时需要访问第三方(愚蠢的)数据.
    • 一般来说,这不是一个答案,而是一个评论。我还没有投反对票。
    • 是的,sometimes one need to access third party (stupid) data。我只是指出不要在 SQL 中这样做。
    猜你喜欢
    • 1970-01-01
    • 2019-11-25
    • 1970-01-01
    • 2021-08-28
    • 2019-08-01
    • 1970-01-01
    • 2022-01-08
    • 2019-12-02
    • 1970-01-01
    相关资源
    最近更新 更多