RETURNING
这是可能的单程往返到数据库:
INSERT INTO tbl(filename)
VALUES ('my_filename')
RETURNING tbl_id;
tbl_id
通常是一个serial or IDENTITY(Postgres 10 或更高版本)列 https://stackoverflow.com/a/9875517/939860. 手册中有更多内容 https://www.postgresql.org/docs/current/sql-insert.html.
显式获取值
If filename
需要包括tbl_id
(冗余地),您仍然可以使用单个查询。
Use lastval() https://www.postgresql.org/docs/current/functions-sequence.html或者更具体的currval() https://www.postgresql.org/docs/current/functions-sequence.html:
INSERT INTO tbl (filename)
VALUES ('my_filename' || currval('tbl_tbl_id_seq') -- or lastval()
RETURNING tbl_id;
See:
- 同一 INSERT 期间另一列中串行列的参考值 https://stackoverflow.com/questions/12433075/reference-value-of-serial-column-in-another-column-during-same-insert/12433446#12433446
如果在此过程中可以推进多个序列(即使通过触发器或其他副作用)sure方法是使用currval('tbl_tbl_id_seq')
.
序列名称
The 字符串字面量 'tbl_tbl_id_seq'
在我的例子中应该是actual序列的名称并被转换为regclass
,如果在当前中找不到该名称的序列,则会引发异常search_path https://stackoverflow.com/a/9067777/939860.
tbl_tbl_id_seq
是自动生成的表的默认值tbl
带串行列tbl_id
。但没有任何保证。列默认值可以从中获取值any序列(如果如此定义)。如果创建表时使用默认名称,Postgres 将根据简单的算法选择下一个可用名称。
如果你不这样做knowa 的序列名称serial
列,使用专用功能pg_get_serial_sequence() https://www.postgresql.org/docs/current/functions-info.html#FUNCTIONS-INFO-CATALOG-TABLE。可以即时完成:
INSERT INTO tbl (filename)
VALUES ('my_filename' || currval(pg_get_serial_sequence('tbl', 'tbl_id'))
RETURNING tbl_id;
db<>fiddle
Old sqlfiddle http://www.sqlfiddle.com/#!15/7a179/3