在创建用户所有评论的 table 时,使用 SERIAL 作为主键是否合适?

Is using SERIAL fine for the primary key when creating a table of all the comments made by users?

我在使用 mongodb 一段时间后正在尝试学习 postgres,我想知道如何为每个 comment.

设置唯一的 ID

我有一个外键 userId,用户为其创建了评论,但对于主键,我需要某种 commentId。我的 commentId 可以使用 SERIAL 吗?或者,有没有像 UUID 这样更好的方法?我不知道我是否需要迁移数据。

由于您对评论 ID 的实际值不感兴趣(只是它存在并且是唯一的),serial 是此类列的不错选择。请注意,在现代 PostgreSQL 数据库(自 7.3 起)中,创建 serial 并不自动意味着它将具有唯一约束,因此您必须明确地处理它。例如:

CREATE TABLE comments (
    comment_id SERIAL PRIMARY KEY,
    user_id INT REFERENCES users(id), -- You should probably also index it
    comment VARCHAR(200) -- Or any other reasonable size
)

编辑:
要回答评论中的问题,可以为 UUID 列创建类似的行为,方法是为其指定新生成的 UUID.

的默认值

首先,您必须安装 postgres-contrib` 包(如果您尚未安装)。例如,在基于 Red Hat 的 linux 上,您可以 运行(作为 root):

$ dnf install postgresql-contrib

然后,您需要从特权用户创建扩展:

CREATE EXTENSION IF NOT EXISTS "uuid-ossp";

这将创建一个您可以使用的 generate_uuid_v1 函数:

CREATE TABLE comments (
    comment_id UUID DEFAULT UUID_GENERATE_V1() PRIMARY KEY,
    user_id INT REFERENCES users(id), -- You should probably also index it
    comment VARCHAR(200) -- Or any other reasonable size
)