我想使用序列为我的数据库中的某些对象创建友好的ID.我的问题是我不希望序列对表是全局的,而是我想基于外键增加值.
例如,我的表定义为:
CREATE TABLE foo (id numeric PRIMARY KEY, friendly_id SERIAL, bar_id numeric NOT NULL)
Run Code Online (Sandbox Code Playgroud)
我想friendly_id分别为每个增加bar_id以下声明:
INSERT INTO foo (123, DEFAULT, 345)
INSERT INTO foo (124, DEFAULT, 345)
INSERT INTO foo (125, DEFAULT, 346)
INSERT INTO foo (126, DEFAULT, 345)
Run Code Online (Sandbox Code Playgroud)
会导致(期望的行为):
id | friendly_id | bar_id
-----------+------------------+-----------------
123 | 1 | 345
124 | 2 | 345
125 | 1 | 346
126 | 3 | 345
Run Code Online (Sandbox Code Playgroud)
而不是(当前行为):
id | friendly_id | bar_id
-----------+------------------+-----------------
123 | 1 | 345
124 | 2 | 345
125 | 3 | 346
126 | 4 | 345
Run Code Online (Sandbox Code Playgroud)
这可能是使用序列还是有更好的方法来实现这一目标?
create table foo (
id serial primary key,
friendly_id integer not null,
bar_id integer not null,
unique(friendly_id, bar_id)
);
Run Code Online (Sandbox Code Playgroud)
在应用程序中将插入包装在异常捕获循环中,以便在引发重复键异常时重试
insert into foo (friendly_id, bar_id)
select
coalesce(max(friendly_id), 0) + 1,
346
from foo
where bar_id = 346
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
884 次 |
| 最近记录: |