如何为PostgreSQL序列指定值列表 [英] How to specify list of values for a postgresql sequence

查看:353
本文介绍了如何为PostgreSQL序列指定值列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个整数值 X 的列表,我希望表 Y 的主键来自该整数值列表。我想知道是否可以使用序列来完成。换句话说:有没有办法告诉PostgreSQL序列使用此列表 X 为我的表 Y

I have a list of integer values X and I want a primary key for my table Y to come from that list of integer values. I was wondering if this could be done using sequences. In other words: is there a way to tell a PostgreSQL sequence to use this list X to generate primary keys for my table Y?

一种执行此操作的方法是使用一个序列,该序列包含列表 X ,在序列上调用 setval(),获取下一个值,然后尝试将其插入到我的表 Y 中。如果存在并发请求,则会出现错误,在这种情况下,我需要尝试使用列表 X 中的下一个值。我想知道还有什么其他(更好的)方法可以实现我的目标。

One way of doing this would be to use a sequence that contains the index of the last used integer from the list X, call setval() on the sequence, get the next value and try to insert it into my table Y. In case of concurrent requests there will be an error, in which case I need to try with the next value from the list X. I would like to know what other (better) ways there are to achieve what I intend to do.

推荐答案

可以像这样工作:

-- DROP SCHEMA x CASCADE;
CREATE SCHEMA x;
CREATE TABLE x.priv_id(seq_id int primary key, id int);

INSERT INTO x.priv_id
SELECT generate_series(1,100,1), (random() * 1000)::int;

CREATE SEQUENCE x.priv_seq;

SELECT id
FROM   x.priv_id
WHERE  seq_id = (SELECT nextval('x.priv_seq'));



要点:



1)创建包含两个数字的查找表

- seq_id 从1和您的主键开始计数。

- id 是序列中的数字(我在这里替换了随机数)。

2)创建一个辅助序列。

3)用一个像上面一样进行选择。

您需要子选择,否则所有值将立即返回。

Major points:

1) Create a lookup table with two numbers
- seq_id is counting from 1 and your primary key.
- id is your numbers in sequence (I substituted random numbers here).
2) Create a helper sequence.
3) Get your numbers with a SELECT like above.
You need the subselect, or all values will be returned at once.

此解决方案提供了所有安全性 nextval()必须提供并发性。

创建如果要确保自定义ID是唯一的,请在priv_id(id)上使用唯一索引。

This solution gives all the security nextval() has to offer for concurrency.
Create a unique index on priv_id(id) if you want to make sure your custom id's are unique.

这篇关于如何为PostgreSQL序列指定值列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆