【问题标题】:Insert into a table with sequence of numbers appended to a value插入带有附加到值的数字序列的表中
【发布时间】:2021-05-04 05:07:32
【问题描述】:

我正在使用 postgres Sql,我打算在表中插入一百万条记录。但是,对于其中一列,我想插入一个附加了一个数字并按顺序增加的值。例如:

在上面的示例中,pxinsname 和 key 具有递增的值,并附加了一个常量文本(S-,ABC)

我不确定如何逐步增加这些列中的值。尝试使用以下查询 -

insert into testable (
    pxcommitdatetime,pxsavedatetime,pxcreatedatetime,pxcreateoperator,pxcreateopname,pxinsname,key,tripname, source, destination, passengername,passengerage
)
select
CURRENT_TIMESTAMP,
CURRENT_TIMESTAMP,
CURRENT_TIMESTAMP,
test,
test,
// S- "Incremental value",
// ABC S "Incremental value",
    md5(random()::text),
    md5(random()::text),
    md5(random()::text),
    md5(random()::text),
    left(md5(random()::text), 4)
from generate_series(1, 10) s(i)

【问题讨论】:

  • 为什么不直接使用s.i

标签: sql postgresql sql-insert


【解决方案1】:

为此,您可以使用序列: https://www.postgresql.org/docs/current/sql-createsequence.html

首先你需要创建它:

CREATE SEQUENCE key_seq START 1;

然后在您的查询中使用如下:

insert into testable (
    pxcommitdatetime,pxsavedatetime,pxcreatedatetime,pxcreateoperator,pxcreateopname,pxinsname,key,tripname, source, destination, passengername,passengerage
)
select
CURRENT_TIMESTAMP,
CURRENT_TIMESTAMP,
CURRENT_TIMESTAMP,
test,
test,
// S- "Incremental value",
 "ABC S" || nextval('key_seq')::text,
    md5(random()::text),
    md5(random()::text),
    md5(random()::text),
    md5(random()::text),
    left(md5(random()::text), 4)
from generate_series(1, 10) s(i)

【讨论】:

  • 好的。但是每次我尝试在同一个查询中使用序列号时,这都会生成下一个值。我可以将下一个值存储在变量中并在我的列中使用该变量吗?如何将值存储在查询中的变量中?
  • Sequence 还提供了 currval 函数,所以你可以先用 nextval(),再用 currval()
  • 你为什么不用s.i
猜你喜欢
  • 1970-01-01
  • 2023-03-23
  • 1970-01-01
  • 1970-01-01
  • 2020-07-12
  • 2013-10-06
  • 1970-01-01
  • 2019-12-11
相关资源
最近更新 更多