[英]What column type should UUID be in postgreSQL?
I would like to use UUIDs has my primary key, and I am generating them using the built-in gen_random_uuid()
expression for DEFAULT
.我想使用 UUID 有我的主键,我正在使用
DEFAULT
的内置gen_random_uuid()
表达式生成它们。
However, I don't know what column type to use for UUIDs.但是,我不知道 UUID 使用什么列类型。 When I use
uuid
or UUID
, I get the following error:当我使用
uuid
或UUID
时,出现以下错误:
PostgreSQL said: column "id" cannot be cast automatically to type uuid Hint: You might need to specify "USING id::uuid".
PostgreSQL said: column "id" cannot be cast automatically to type uuid 提示:您可能需要指定“USING id::uuid”。
Is there a native UUID column type?是否有本机 UUID 列类型? Should I just be using varchar(255)?
我应该只使用 varchar(255) 吗?
Thanks.谢谢。
PostgreSQL supports a UUID data type 'out of the box' indeed: https://www.postgresql.org/docs/current/datatype-uuid.html PostgreSQL 确实支持“开箱即用”的 UUID 数据类型: https://www.postgresql.org/docs/current/datatype-uuid.html
Here's an example of how you might define a table with a UUID primary key using the uuid data type: CREATE TABLE users ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), name TEXT NOT NULL, email TEXT NOT NULL );
这是一个示例,说明如何使用 uuid 数据类型定义具有 UUID 主键的表:
CREATE TABLE users ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), name TEXT NOT NULL, email TEXT NOT NULL );
In this example, we are creating a table called users with three columns: id, name, and email. The id column is of type uuid and is the primary key of the table.在此示例中,我们创建了一个名为 users 的表,其中包含三列:id、name 和 email。id 列的类型为 uuid,是该表的主键。 The DEFAULT clause specifies that the gen_random_uuid() expression should be used to generate a new UUID value for the id column if no value is provided when inserting a new row.
DEFAULT 子句指定如果在插入新行时未提供值,则应使用 gen_random_uuid() 表达式为 id 列生成新的 UUID 值。
If you are getting an error when trying to use the uuid data type, it is possible that you are using a version of PostgreSQL that does not support this data type.如果您在尝试使用 uuid 数据类型时遇到错误,则可能是您使用的 PostgreSQL 版本不支持此数据类型。 In this case, you can use the text data type to store UUID values as text strings.
在这种情况下,您可以使用文本数据类型将 UUID 值存储为文本字符串。
To cast a text string to a UUID value in PostgreSQL, you can use the::uuid operator.要将文本字符串转换为 PostgreSQL 中的 UUID 值,您可以使用 ::uuid 运算符。 For example:
例如:
SELECT '2c27c970-33ab-11eb-adc1-0242ac120002'::uuid;
This will return the UUID value represented by the text string.这将返回由文本字符串表示的 UUID 值。 You can use this operator in your INSERT and SELECT statements to cast text strings to UUID values as needed.
您可以在 INSERT 和 SELECT 语句中使用此运算符,根据需要将文本字符串转换为 UUID 值。
Keep in mind that using the text data type for UUID values may be less efficient than using the uuid data type, as the uuid data type is specifically designed for storing and manipulating UUID values.请记住,为 UUID 值使用文本数据类型可能比使用 uuid 数据类型效率低,因为 uuid 数据类型是专门为存储和操作 UUID 值而设计的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.