在 PostgreSQL 中生成自动递增主键的可接受方法是什么?
没有序列和触发器就没有简单的方法来做到这一点吗?我的 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)
);
Is there no easy way to do this without sequences and triggers? I have average SQL skills, and I want to use the industry standard method for pl/sql (PostgreSQL). I'm basically converting over this example table from 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));
What I have so far:
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)
);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
标准方法是使用
serial 或
bigserial
:
因此,您可以使用如下内容创建表:
serial
和bigserial
类型确实会在幕后创建序列,但您永远不必直接使用该序列。The standard way would be to use
serial
orbigserial
:So you'd create the table with something like this:
The
serial
andbigserial
types do create a sequences behind the scenes but you never have to work with the sequence directly.在 PostgreSQL 10 中,您可以使用
身份列
。这是示例:另外:
In PostgreSQL 10 you can use
identity columns
. Here is example:Additionally: