我正在使用UUID版本1作为主键。我想按照UUID v1的时间戳进行排序。目前,如果我执行类似以下操作:
SELECT id, title
FROM table
ORDER BY id DESC;
PostgreSQL没有按照UUID时间戳对记录进行排序,而是按照UUID字符串表示进行排序,在我的情况下导致了意外的排序结果。
我有什么遗漏的吗?或者在PostgreSQL中没有内置的方法可以做到这一点?
我正在使用UUID版本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));
select id :: timestamp,title from table order by id :: timestamp desc
- Santhucooluuid v1
吗?我尝试过uuid_generate_v4
,并且仅尝试了您的查询,它可以正常工作。 - Santhucool