PostgreSQL-按UUID版本1时间戳排序

PostgreSQL-按UUID版本1时间戳排序,postgresql,sorting,timestamp,uuid,Postgresql,Sorting,Timestamp,Uuid,我使用的是主键。我想在UUIDV1时间戳上排序。现在如果我这样做: SELECT id, title FROM table ORDER BY id DESC; PostgreSQL不按UUID时间戳对记录进行排序,而是按UUID字符串表示对记录进行排序,在我的例子中,这会导致意外的排序结果 我是否遗漏了什么,或者PostgreSQL中没有内置的方法来实现这一点?时间戳是v1 UUID的一部分。自1582-10-15 00:00以来,它以十六进制格式存储为数百纳秒。此函数用于提取时间戳: c

我使用的是主键。我想在UUIDV1时间戳上排序。现在如果我这样做:

SELECT id, title 
FROM table 
ORDER BY id DESC;
PostgreSQL不按UUID时间戳对记录进行排序,而是按UUID字符串表示对记录进行排序,在我的例子中,这会导致意外的排序结果


我是否遗漏了什么,或者PostgreSQL中没有内置的方法来实现这一点?

时间戳是v1 UUID的一部分。自
1582-10-15 00:00以来,它以十六进制格式存储为数百纳秒。此函数用于提取时间戳:

create or replace function uuid_v1_timestamp (_uuid uuid)
returns timestamp with time zone as $$

    select
        to_timestamp(
            (
                ('x' || lpad(h, 16, '0'))::bit(64)::bigint::double precision -
                122192928000000000
            ) / 10000000
        )
    from (
        select
            substring (u from 16 for 3) ||
            substring (u from 10 for 4) ||
            substring (u from 1 for 8) as h
        from (values (_uuid::text)) s (u)
    ) s
    ;

$$ language sql immutable;

select uuid_v1_timestamp(uuid_generate_v1());
       uuid_v1_timestamp       
-------------------------------
 2016-06-16 12:17:39.261338+00
12219292800000000
是公历开始和Unix时间戳之间的间隔

在您的查询中:

select id, title
from t
order by uuid_v1_timestamp(id) desc
为了提高性能,可以在以下基础上创建索引:

create index uuid_timestamp_ndx on t (uuid_v1_timestamp(id));

你试过这样的东西吗<代码>选择id::timestamp,表中的标题按id::timestamp desc排序
,这会给我一个错误。错误:无法将类型uuid强制转换为时间戳是否必须使用
uuid v1
?我已经尝试了
uuid\u generate\u v4
并简单地尝试了您的查询,它工作得很好。如果您只想按“原始”时间戳排序(而不关心将其转换为unix历元时间戳)?