sql - 如何使用 nextval() 在字符串中插入包含其自己 ID 的行

标签 sql postgresql sql-insert auto-increment create-table

我有一个表,其中有一列,该列中的字符串包含其自己的 ID。 如何使用单个 SQL 语句插入新行?

id| URL
--|----------------------
 1|"http://example.com/1"
 2|"http://example.com/2"
 3|"http://example.com/3"

我需要类似的东西

NEXT_ID = SELECT nextval('table_name_id_seq');
insert into table_name (id, name) values (NEXT_ID, 'http://example.com/' + NEXT_ID) returning *

https://www.db-fiddle.com/f/3NwLNBirN7mHKpDk9NyHSy/1

最佳答案

一个选项是首先选择子查询中的下一个序列:

insert into test(id, url)
select id, 'http://example.com/' || id::text
from (select nextval('test_id_seq') as id) x;

您还可以使用计算列来代替更干净的插入代码:

create table test(
  id SERIAL,
  url text,
  new_url text generated always as (url || id::text) stored
);

insert into test(url) values ('http://example.com/');

给你:

| id  | url                 | new_url              |
| --- | ------------------- | -------------------- |
| 1   | http://example.com/ | http://example.com/1 |

关于sql - 如何使用 nextval() 在字符串中插入包含其自己 ID 的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63927279/

相关文章:

mysql - 选择 * 从表中 1 = 2

MySQL:条件连接不显示用于计算纬度/经度之间距离的所有数据

python - 通过 Python 使用 BULK INSERT

php - 为什么我的 PHP 代码在运行时返回空白页?

Mysql 每月分区 - 错误代码 : 1503 A PRIMARY KEY must include all columns in the table's partitioning function

sql - 使用 postgresql 数据库存储 NULL 值需要多少磁盘空间?

postgresql - 即使多个 session 在 postgresql 中调用它们,也可以让存储过程一个接一个地运行

postgresql - 使用 Unix 时间戳值将 CSV 数据复制到 Postgres

mysql - 将值插入表中的新列,根据同一表中的数据计算

sql - 使用 table2、table3 合并到 Table1(多个条件)?缺少语法