我的最终目标是构建一个JSON_OBJECT()
select 语句,它只从存储的 json 值中收集几个值。
我当前的 select 语句迭代:
SELECT
JSON_OBJECT(
'id', document->>'$.id',
'slug', document->>'$.slug',
'title', document->>'$.title',
'date_published', document->>'$.date_published',
'toc', (SELECT JSON_OBJECT('title', document->>'$.toc[*][*].title') WHERE document->>'$.id' = document->>'$.id' )
) as document
FROM documents
WHERE
`type` = "item" AND
NOW() > date_published;
示例item
文档可能在哪里:
{
"id": "d434089d-33ac-11e8-af1c-005056a40c60",
"toc": [
[
{
"id": "d4e1e442-57a9-11e8-af1c-005056a40c60",
"slug": "0-intro",
"chunk": 0,
"index": 0,
"pages": [],
"title": "Intro",
"urlsuffix": ""
},
{
"id": "d4e1ef07-57a9-11e8-af1c-005056a40c60",
"slug": "1-beginning",
"chunk": 0,
"index": 1,
"pages": [
{
"id": "d4e1f726-57a9-11e8-af1c-005056a40c60",
"slug": "2-nested-example",
"chunk": 0,
"index": 2,
"pages": [],
"title": "Nested Example",
"urlsuffix": ""
},
{
"id": "d4e1fee4-57a9-11e8-af1c-005056a40c60",
"slug": "3-three-layers-deep",
"chunk": 0,
"index": 3,
"pages": [
{
"id": "d4e2065e-57a9-11e8-af1c-005056a40c60",
"slug": "4-four-in",
"chunk": 0,
"index": 4,
"pages": [],
"title": "Four In",
"urlsuffix": ""
},
{
"id": "d4e20e47-57a9-11e8-af1c-005056a40c60",
"slug": "5-maximum-nesting",
"chunk": 0,
"index": 5,
"pages": [],
"title": "This is likely the maximum amount of Nesting",
"urlsuffix": ""
}
],
"title": "Three Layers Deep",
"urlsuffix": ""
},
{
"id": "d4e2168b-57a9-11e8-af1c-005056a40c60",
"slug": "6-follow-up-chapter",
"chunk": 0,
"index": 6,
"pages": [],
"title": "Follow-up Chapter",
"urlsuffix": ""
}
],
"title": "The Beginning",
"urlsuffix": ""
}
]
],
"slug": "an-item",
"tags": [
"test-item"
],
"type": "item",
"title": "An Item",
"download": null,
"date_added": "1522342602",
"page_count": null,
"description": "",
"date_published": "1522238400"
}
这就是我试图作为 select 语句的结果记录来完成的(对于示例文档):
{
"id": "d434089d-33ac-11e8-af1c-005056a40c60",
"slug": "an-item",
"title": "An Item",
"date_published": "1522238400",
"toc": [
{
"id": "d4e1e442-57a9-11e8-af1c-005056a40c60",
"slug": "0-intro",
"title": "Intro",
"urlsuffix": ""
},
{
"id": "d4e1ef07-57a9-11e8-af1c-005056a40c60",
"slug": "1-beginning",
"title": "The Beginning",
"urlsuffix": ""
}
]
}
所以基本上,只是一个顶级目录项的数组(深度[1])
如果我绝对必须的话,我会承认在应用程序中完成逻辑,我只是觉得必须有一种方法可以使用 MySQL json 函数来做到这一点。
选择对象/数组时有没有办法要求最大深度?
我正在使用 5.7.22,所以我确实拥有最新的花哨 json 功能(JSON_ARRAYAGG/JSON_OBJECTAGG 等)