如何在 PostgreSQL 中创建 guid

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31247735/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 06:01:21  来源:igfitidea点击:

How to create guid in PostgreSQL

postgresqlplpgsqlguid

提问by Andrus

How to create GUID in Windows format in Postgres 9.0+?

如何在 Postgres 9.0+ 中创建 Windows 格式的 GUID?

I tried function

我试过功能

CREATE or REPLACE FUNCTION public.getguid() RETURNS varchar AS $BODY$ 
DECLARE 
  v_seed_value varchar(32); 
BEGIN 
  select 
    md5( 
      inet_client_addr()::varchar || 
      timeofday() || 
      inet_server_addr()::varchar || 
      to_hex(inet_client_port()) 
    ) 
  into v_seed_value; 

  return (substr(v_seed_value,1,8) || '-' || 
          substr(v_seed_value,9,4) || '-' || 
          substr(v_seed_value,13,4) || '-' || 
          substr(v_seed_value,17,4) || '-' || 
          substr(v_seed_value,21,12)); 
END; $BODY$ LANGUAGE 'plpgsql' VOLATILE SECURITY DEFINER;

from

http://postgresql.1045698.n5.nabble.com/newid-in-postgres-td1879346.html

http://postgresql.1045698.n5.nabble.com/newid-in-postgres-td1879346.html

Tried

试过

select getguid()
union all
select getguid()

but it returns same values

但它返回相同的值

"c41121ed-b6fb-c9a6-bc9b-574c82929e7e"
"c41121ed-b6fb-c9a6-bc9b-574c82929e7e"

How to fix this so that unique rows are returned?

如何解决这个问题,以便返回唯一的行?

回答by Patrick

PostgreSQL has the uuid-osspextension which ships with the standard distributions and it has 5 standard algorithms for generating uuids. Note that a guidis the Microsoft version of a uuid, conceptually they are the same thing.

PostgreSQL 有uuid-ossp标准发行版附带的扩展,它有 5 种生成uuids 的标准算法。请注意, aguid是a的 Microsoft 版本uuid,从概念上讲它们是相同的。

CREATE EXTENSION "uuid-ossp";

Then:

然后:

SELECT uuid_generate_v4();

Note also that, once you installed the extension, PostgreSQL has an actual binary uuidtype, with a length of 16 bytes. Working with the binary type is much faster than working with the text equivalent and it takes up less space. If you do need the string version, you can simply cast it to text:

还要注意的是,一旦你安装了扩展,PostgreSQL 就有一个实际的二进制uuid类型,长度为 16 个字节。使用二进制类型比使用等效文本快得多,而且占用的空间更少。如果您确实需要字符串版本,您可以简单地将其转换为text

SELECT uuid_generate_v4()::text;