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

标签 postgresql sorting timestamp uuid

我正在使用 UUID version 1作为主键。我想对 UUID v1 时间戳进行排序。现在,如果我做这样的事情:

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

122192928000000000 是公历开始和 Unix 时间戳之间的间隔。

在您的查询中:

select id, title
from t
order by uuid_v1_timestamp(id) desc

为了提高性能,可以在其上创建索引:

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

关于PostgreSQL - 按 UUID 版本 1 时间戳排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37713131/

相关文章:

sql - 如何对 PostgreSQL JSON 字段进行排序

postgresql - Fix 必须出现在 GROUP BY 子句中或用于聚合函数中

python - 从排序数组到排序多项式数组的算法

java - 类不会计算它应该计算的内容,也是 : sorting arrays of objects?

postgresql - psql版本和postgresql版本不匹配怎么办?

新列的 Postgresql 更新缓慢

java - 比较排序算法

c - 如何打印从 pcap 文件读取的数据包的时间戳?

php - 可以将 PHP date() 与数组项一起使用吗?

python - pandas 数据帧按类和时间戳分组