我正在使用 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/