没有序列和触发器就没有简单的方法吗?我的 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)
);
serial
和 bigserial
类型确实在幕后创建了一个序列,但您永远不必直接使用该序列。
关于postgresql - 在 PostgreSQL 中生成自动递增主键的可接受方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5998406/