You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PostgreSQL中如何为从视图批量插入表的数据生成连续序列id?

可直接运行的PostgreSQL实现语句

使用PostgreSQL内置的row_number()窗口函数即可在查询层面生成连续的id_值:

insert into xyz_table (id_, column1, column2, 
column3, column4, column5) 
select 
  row_number() over() as id_,
  a.column1, 
  a.column2, 
  a.column3, 
  a.column4, 
  a.column5
from xyz_view a;

扩展场景(接续已有最大ID生成)

如果需要id_值接续xyz_table中已有的最大id生成,避免主键冲突,可以调整id_的生成逻辑:

insert into xyz_table (id_, column1, column2, 
column3, column4, column5) 
select 
  -- 若xyz_table为空则从1开始生成
  row_number() over() + coalesce((select max(id_) from xyz_table), 0) as id_,
  a.column1, 
  a.column2, 
  a.column3, 
  a.column4, 
  a.column5
from xyz_view a;

如果需要按指定字段的顺序生成id,可在over()中添加order by子句,示例:row_number() over(order by a.column1 desc) as id_

内容的提问来源于stack exchange,提问作者Pent Terry

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 11:45:05