基于外键增加PostgreSQL中的序列

前端之家收集整理的这篇文章主要介绍了基于外键增加PostgreSQL中的序列前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想使用序列为我的数据库中的某些对象创建友好的ID.我的问题是我不希望序列对表是全局的,而是我想基于外键增加值.

例如,我的表定义为:

CREATE TABLE foo (id numeric PRIMARY KEY,friendly_id SERIAL,bar_id numeric NOT NULL)

我希望friendly_id为每个bar_id分别增加,以便以下语句:

INSERT INTO foo (123,DEFAULT,345)
INSERT INTO foo (124,345)
INSERT INTO foo (125,346)
INSERT INTO foo (126,345)

会导致(期望的行为):

id         | friendly_id      | bar_id
-----------+------------------+-----------------
123        | 1                | 345
124        | 2                | 345
125        | 1                | 346
126        | 3                | 345

而不是(当前行为):

id         | friendly_id      | bar_id
-----------+------------------+-----------------
123        | 1                | 345
124        | 2                | 345
125        | 3                | 346
126        | 4                | 345

这可能是使用序列还是有更好的方法来实现这一目标?

解决方法

create table foo (
    id serial primary key,friendly_id integer not null,bar_id integer not null,unique(friendly_id,bar_id)
);

在应用程序中将插入包装在异常捕获循环中,以便在引发重复键异常时重试

insert into foo (friendly_id,bar_id)
select
    coalesce(max(friendly_id),0) + 1,346
from foo
where bar_id = 346

猜你在找的Postgre SQL相关文章