PostgreSQL - 按嵌套数组中的日期排序

PostgreSQL - ORDER BY a date in nested array

我有以下数据结构:

[
 {
   "postID": 1, 
   "images": [
      {"imageID": 1, "pos": 1, "uploaded": "2022-01-01", "tags": []}, 
      {"imageID": 2, "pos": 2, "uploaded": "2022-01-01", "tags": []}
    ]
 },
 {
   "postID": 2, 
   "images": [
      {"imageID": 3, "pos": 1, "uploaded": "2022-01-01", "tags": []}, 
      {"imageID": 4, "pos": 2, "uploaded": "2022-01-01", "tags": []}
    ]
 }
]

如何为每个 post 按最近(或最旧)的日期排序,其中从每张图像中选择的日期最多 recent/oldest?请注意,我仍然希望根据“pos”列维护图像的顺序。

这是我生成此数据的查询:

WITH image_tags AS (
    SELECT images."post id", 
           json_build_object (
               'imageID', images."image id",
               'uploaded', images."uploaded",
               'tags', json_agg("tag map".tag) ) AS image
    FROM images
    JOIN "tag map" ON images."image id" = "tag map"."image id"
    GROUP BY images."post id", images."image id"
    ORDER BY images."pos" DESC
)
SELECT posts."post id" AS "postID", 
       json_agg(image_tags.image) AS images
FROM posts
JOIN image_tags ON posts."post id" = image_tags."post id"
GROUP BY posts."post id"
--ORDER BY ?

可能的替代方案:我将上传日期移至 post table,但这意味着我无法找到每张图片的单独上传日期。因此,只有在无法做到这一点时,这才是最后的手段。

您的 images table 中包含所有必要的信息。 (由于您没有显示 table 的定义,接下来是假设一些事情。)window 函数应该可以解决问题:

WITH image_tags AS (
    SELECT images."post id", 
           json_build_object (
               'imageID', images."image id",
               'uploaded', images.uploaded,
               'tags', json_agg("tag map".tag) ) AS image,
           first_value(images.uploaded) OVER (
               PARTITION BY images."post id" ORDER BY images.uploaded DESC
               ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING ) AS newest,
    FROM images
    JOIN "tag map" ON images."image id" = "tag map"."image id"
    GROUP BY images."post id", images."image id"
    ORDER BY images."pos" DESC
)
SELECT posts."post id" AS "postID", 
       json_agg(image_tags.image) AS images
FROM posts
JOIN image_tags USING ("post id")
GROUP BY posts."post id"
ORDER BY image_tags.newest -- ASC by default, use DESC for reverse order

window function 获取 images table 中具有相同 "post id" 的所有行,并使它们可用于分析。然后,您可以找到 window 帧的第一行和最后一行,并将值存储在 image_tags 行源的新列中。之后主查询中的排序就很简单了。