如何在SQL Server中查询具有JSON列的表,其中JSON列可以导致0行或多行?

huangapple go评论54阅读模式
英文:

How do I query a table in SQL Server that has a JSON column, where that JSON column can result in 0 or Many rows?

问题

我有一个表格 my_table。以下是一个简化的视图:

id, the_json
1, {json json json}
2, {json}
3, {json json}

这里是 JSON 可能的样本:

{
    "valid": false,
    "messages": {
        {
            "message": "blah",
            "error": true,
            "detail": "something1"
        }
        {
            "message": "blah blah",
            "error": true,
            "detail": "something2"
        }
        {
            "message": "blah blah blah",
            "error": false,
            "detail": "something3"
        }
    }
}

我正在尝试编写一个查询以获得以下结果(为了可读性添加了行间隔):

id, message, error, detail

1, blah, true, something1
1, blah blah, true, something2
1, blah blah blah, false, something3

2, blah, true, something1

3, blah, true, something1
3, blah blah, true, something2

也就是说,JSON 中的每个消息节点都应该产生一行,并且应该与父表连接以显示 id。

英文:

I have a table my_table. Here is a simplified view:

id, the_json
1, {json json json}
2, {json}
3, {json json}

Here is a sample of what the JSON can look like:

{
    "valid":false,
    "messages": {
        {
            "message": "blah",
            "error": true,
            "detail": "something1"
        }
        {
            "message": "blah blah",
            "error": true,
            "detail": "something2"
        }
        {
            "message": "blah blah blah",
            "error": false,
            "detail": "something3"
        }
    }
}

I am trying to write a query to get the following result (row gaps for visibility):

id, message, error, detail

1, blah, true, something1
1, blah blah, true, something2
1, blah blah blah, false, something3

2, blah, true, something1

3, blah, true, something1
3, blah blah, true, something2

Aka, each message node in the json should result in a row, and should join back to the parent table to show the id.

答案1

得分: 1

需要使用OPENJSON函数来获取单独的行,并且需要使用模式来获取这些列。要针对表的每一行获取它,您需要使用APPLY

注意使用第二个参数直接跳到$.messages

SELECT
  t.id,
  j.*
FROM YourTable t
CROSS APPLY OPENJSON(t.the_json, '$.messages')
  WITH (
    message nvarchar(100),
    error bit,
    detail nvarchar(100)
  ) j;
英文:

You need to use the OPENJSON function to get separate rows, and you need to do it with a schema to get these columns. To get it per row of your table, you need to APPLY it.

Note the use of a second parameter to jumpt straight to $.messages

SELECT
  t.id,
  j.*
FROM YourTable t
CROSS APPLY OPENJSON(t.the_json, '$.messages')
  WITH (
    message nvarchar(100),
    error bit,
    detail nvarchar(100)
  ) j;

huangapple
  • 本文由 发表于 2023年7月14日 03:17:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/76682598.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定