postgresql - 在 PostgreSQL 中生成自动递增主键的可接受方法是什么?

标签 postgresql auto-increment

没有序列和触发器就没有简单的方法吗?我的 SQL 技能一般,我想使用 pl/sql (PostgreSQL) 的行业标准方法。我基本上是从 Spring Security 转换这个示例表:

create table group_members (
    id bigint generated by default as identity(start with 0) primary key,
    username varchar(50) not null,
    group_id bigint not null,
    constraint fk_group_members_group foreign key(group_id) references groups(id));

我目前拥有的:

CREATE TABLE auth_group_members (
    id NUMBER,
    username VARCHAR(50) NOT NULL,
    group_id NUMBER NOT NULL,
    CONSTRAINT "FK_AuthGroupMembers" FOREIGN KEY(group_id) REFERENCES auth_groups(id)
);

最佳答案

标准方法是使用 serial or bigserial :

The data types serial and bigserial are not true types, but merely a notational convenience for creating unique identifier columns (similar to the AUTO_INCREMENT property supported by some other databases).
[...]
Thus, we have created an integer column and arranged for its default values to be assigned from a sequence generator.

所以你会用这样的东西创建表:

CREATE TABLE auth_group_members (
    id bigserial primary key,
    username VARCHAR(50) NOT NULL,
    group_id NUMBER NOT NULL,
    CONSTRAINT "FK_AuthGroupMembers" FOREIGN KEY(group_id) REFERENCES auth_groups(id)
);

serialbigserial 类型确实在幕后创建了一个序列,但您永远不必直接使用该序列。

关于postgresql - 在 PostgreSQL 中生成自动递增主键的可接受方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5998406/

相关文章:

postgresql - 如何禁用 AWS RDS 加密?

sql - 控制到达功能结束而没有 RETURN

database - 添加约束以使每组行的列唯一

postgresql - 在 Postgresql 中选择未锁定的行

sql - POSTGRES - 使用 ON CONFLICT DO NOTHING 防止串行递增

sqlite - 如何对具有主键和 UNIQUE 列的表执行更新插入

postgresql - 通过不同的名称关联同一个模型两次

mysql - phpmyadmin 不再让我设置 auto_increment 值

c++ - 使用 "Curiously Recurring Template Pattern"的增量数

sqlite - SQLite主键不起作用