使用 unnest 函数插入 - 跳过序列列中的数字

MAH*_*AHI 1 arrays postgresql function auto-increment

我试图在插入中使用“unnest”功能,
这样做时,序列会为每个插入跳过一个数字,
请帮我解决这个问题...

mydb=# \d tab1  
                         Table "public.tab1"  
 Column |  Type   |                     Modifiers                         
--------+---------+---------------------------------------------------  
 id     | integer | not null default nextval('tab1_id_seq'::regclass)  
 col1   | integer |   
 col2   | integer |   
Indexes:  
    "tab1_pkey" PRIMARY KEY, btree (id)  

mydb=# insert into tab1(id,col1,col2) values (nextval('tab1_id_seq'),1,unnest(array[4,5]));  
INSERT 0 2  
mydb=# select * from tab1;  
 id | col1 | col2   
----+------+------  
  1 |    1 |    4  
  2 |    1 |    5  
(2 rows)  

mydb=# insert into tab1(id,col1,col2) values (nextval('tab1_id_seq'),2,unnest(array[4,5]));  
INSERT 0 2  
mydb=# select * from tab1;  
 id | col1 | col2   
----+------+------  
  1 |    1 |    4  
  2 |    1 |    5  
  4 |    2 |    4  
  5 |    2 |    5  
(4 rows)  

mydb=# insert into tab1(col1,col2) values(2,unnest(array[4,5]));  
INSERT 0 2  
mydb=# select * from tab1;  
 id | col1 | col2   
----+------+------  
  1 |    1 |    4  
  2 |    1 |    5  
  4 |    2 |    4  
  5 |    2 |    5  
  7 |    2 |    4  
  8 |    2 |    5  
(6 rows)  

mydb=# insert into tab1(col2) values(unnest(array[4,5]));  
INSERT 0 2  
mydb=# select * from tab1;  
 id | col1 | col2   
----+------+------  
  1 |    1 |    4  
  2 |    1 |    5  
  4 |    2 |    4  
  5 |    2 |    5  
  7 |    2 |    4  
  8 |    2 |    5  
 10 |      |    4  
 11 |      |    5  
(8 rows)  

mydb=# select nextval('tab1_id_seq');  
 nextval   
---------  
      13  
(1 row)  
Run Code Online (Sandbox Code Playgroud)

对于每次插入,它都会跳过 id 列中的一个数字,请帮我解决这个问题...

ara*_*nid 5

unnest返回多行,因此在单行中使用它VALUES有点麻烦。尽管它确实有效,但似乎该nextval调用以某种方式被评估了两次。

您可以编写一个插入INSERT INTO ... SELECT ...而不是INSERT INTO ... VALUES: 在 PostgreSQL 中,VALUES它只是一个行构造函数。所以考虑写这样的东西:

insert into tab1(col1, col2) select 1, unnest(array[4,5])
Run Code Online (Sandbox Code Playgroud)