Postgres:Order by ::timestamp asc and desc of jsonb column giving same results,如何按最后一个时间戳排序

Posgres: Order by ::timestamp asc and desc of jsonb column giving same results, how to order by last timestamp

我有这个查询,它根据 table 文档的 UUID doc_id 检索 1 行,它还有一个字段列类型 jsonb:

select 
    DISTINCT ON (doc_id) 
    *
    FROM ( 
        select d.doc_id, c.comments 
        from documents as d 
        cross join lateral jsonb_array_elements(comments) 
        WITH ORDINALITY c(comments)
        WHERE (c.comments ->> 'isUser'):: boolean is false 
        order by (c.comments ->>'timestamp')::timestamp desc
    ) as s;

当我尝试时:

        order by (c.comments ->>'timestamp')::timestamp desc

我得到完全相同的结果。我什至尝试过 timestamptz:

        order by (c.comments ->>'timestamp')::timestamptz asc

jsonb评论栏示例内容:

[...
{
    "text": "30",
    "timestamp": "2018-11-11T09:13:23.242Z", // older
    "isUser": false
},{
    "text": "31",
    "timestamp": "2018-11-11T12:53:48.620Z", // LATEST
    "isUser": false
}]

如您所见,带有文本 30 的对象较旧,但它总是在上面的查询中返回。

该顺序与最终结果无关,因为它仅适用于使用它的 SELECT 语句,即您的子查询。然后,您对这些结果执行另一个查询,使用 DISTINCT ON 执行任何计算,return 您的结果按 some 排序,但可能不是您想要的。

要允许您在外部查询中订购,您要在订单中使用的字段必须在该级别可访问。这意味着子查询还必须 return 时间戳字段,然后外部查询可以对其进行排序但不能 select 它(以保持 returned 列相同)。

select 
    DISTINCT ON (doc_id) 
    doc_id, comments
    FROM ( 
        select d.doc_id, c.comments, (c.comments ->>'timestamp')::timestamp AS comment_timestamp
        from documents as d 
        cross join lateral jsonb_array_elements(comments) 
        WITH ORDINALITY c(comments)
        WHERE (c.comments ->> 'isUser'):: boolean is false 
    ) as s
ORDER BY doc_id, comment_timestamp DESC

我可能遗漏了一些东西,但你似乎根本不需要子查询,这行不行?

select DISTINCT ON (d.doc_id) d.doc_id, c.comments 
from documents as d 
cross join lateral jsonb_array_elements(comments) 
WITH ORDINALITY c(comments)
WHERE (c.comments ->> 'isUser'):: boolean is false 
order by d.doc_id, (c.comments ->>'timestamp')::timestamp desc