【发布时间】:2019-08-10 04:17:44
【问题描述】:
我需要在 CosmosDB 查询编辑器中编写一个 SQL 查询,它将根据我的要求从 Collection 中存储的 JSON 文档中获取结果
JSON 示例
{
"id": "abcdabcd-1234-1234-1234-abcdabcdabcd",
"source": "Example",
"data": [
{
"Laptop": {
"New": "yes",
"Used": "no",
"backlight": "yes",
"warranty": "yes"
}
},
{
"Mobile": [
{
"order": 1,
"quantity": 2,
"price": 350,
"color": "Black",
"date": "07202019"
},
{
"order": 2,
"quantity": 1,
"price": 600,
"color": "White",
"date": "07202019"
}
]
},
{
"Accessories": [
{
"covers": "yes",
"cables": "few"
}
]
}
]
}
要求: 选择特定“日期”的“保修”(笔记本电脑)、“数量”(手机)、“颜色”(手机)、“电缆”(附件)(例如:07202019)
我尝试了以下查询
SELECT
c.data[0].Laptop.warranty,
c.data[1].Mobile[0].quantity,
c.data[1].Mobile[0].color,
c.data[2].Accessories[0].cables
FROM c
WHERE ARRAY_CONTAINS(c.data[1].Mobile, {date : '07202019'}, true)
上述查询的原始输出:
[
{
"warranty": "yes",
"quantity": 2,
"color": "Black",
"cables": "few"
}
]
但是我怎样才能得到这个预期输出,它在数组'Mobile'中包含所有订单详细信息:
[
{
"warranty": "yes",
"quantity": 2,
"color": "Black",
"cables": "few"
},
{
"warranty": "yes",
"quantity": 1,
"color": "White",
"cables": "few"
}
]
由于我编写了 c.data[1].Mobile[0].quantity,即硬编码的“Mobile[0]”,因此输出中仅返回一个条目(即第一个条目),但我想要列出数组中的所有条目
【问题讨论】:
-
嗨,现在有什么进展吗?
-
嗨@JayGong 感谢您的回复,我已经尝试过您的查询,但它只返回 - [ { "quantity": 2, "color": "Black" }, { "quantity": 1 , "color": "White" } ] 它错过了“保修”和“电缆”
-
请看我的新sql。
-
哇,@JayGong 它按预期工作,非常感谢
-
@JayGong 现在我正在尝试实现多个 JOIN,假设在上面的示例 JSON 中我们在附件字段中有更多项目,我尝试了下面的查询,但它没有给我任何结果 (0 -0) SELECT DISTINCT c.data[0].Laptop.warranty, mobile.quantity, mobile.color, Accessories.cables FROM c JOIN data in c.data JOIN mobile in data.Mobile JOIN Accessories in data.Accessories WHERE ARRAY_CONTAINS( data.Mobile, {date : '07202019'}, true) OR ARRAY_CONTAINS(data.Laptop, {New : 'yes'}, true)
标签: arrays azure azure-cosmosdb sql-query-store json-query