如何查询postgres的UUID

我想使用UUID作为标识符,提供前8位数字以确定它是否存在于数据库中。

通常我可以毫无问题地做到这一点:

select * from TABLE where id = 'e99aec55-9e32-4c84-aed2-4a0251584941'::uuid

但这给了我错误:

select * from TABLE where id LIKE 'e99aec55%@'::uuid

错误:

 ERROR: invalid input syntax for uuid: "e99aec55%@" LINE 1: select * from TABLE where id LIKE 'e99aec55... ^ Query failed PostgreSQL said: invalid input syntax for uuid: "e99aec55%@" 

有没有办法在postgresql中查询UUID类型的前n位数?

由于您正在搜索uuid的最高位,您实际上可以between使用(因为uuid比较在PostgreSQL中定义良好):

 ... where some_uuid between 'e99aec55-0000-0000-0000-000000000000' and 'e99aec55-ffff-ffff-ffff-ffffffffffff' 

UUID不作为字符串存储在Postrges中,它们存储为16字节长的二进制值。 因此,以您想要的方式查询它的唯一方法是首先将其转换为字符串,但这种转换的性能将比仅执行相等比较更糟糕。

此外,您还需要维护UUID的字符串表示forms的索引,因此它没有意义。