如何从 INSERT 查询中获取第一个 id
How to get the first id from the INSERT query
假设我们有一个 plpgsql (PostgreSQL 10.7) 函数,其中有一个查询
INSERT INTO "myTable"
SELECT * FROM "anotherTable"
INNER JOIN "otherTable"
...
因此,此查询将向 myTable 中插入几行。在下一个查询中,我想收集在某些条件下插入的 ID。因此,我的想法是执行以下操作:
INSERT INTO "resultTable" rt
SELECT FROM "myTable"
INNER JOIN ...
WHERE rt."id" >= firstInsertedId;
现在的问题是:如何找到这个 firstInsertedId?
我的解决方案:
select nextval(''"myTable.myTable_id_seq"'') into firstInsertedId;
if firstInsertedId > 1 then
perform setval(''"myTable.myTable_id_seq"'', (firstInsertedId - 1));
end if;
我不太喜欢这个解决方案,因为我认为生成 id,然后返回,然后在插入期间再次生成它对性能没有好处。
想法:
- 正在考虑将 id 插入变量数组然后找到最小值,但没有运气。
- 正在考虑使用 lastval() 函数,但似乎没有'
即使在 MySQL LAST_INSERT_ID() 中非常相似的实现中,它也不适合我。
有什么建议吗?
您可以使用 data modifying common table expression 在一条语句中完成这两项操作。你真的不需要PL/pgSQL。
with new_rows as (
INSERT INTO my_table
SELECT *
FROM anotherTable
JOIN "otherTable" ...
returning my_table.id
)
insert into resulttable (new_id)
select id
from new_rows;
另一种选择是将生成的 ID 存储在数组中。
declare
l_ids integer[];
begin
....
with new_rows as (
INSERT INTO my_table
SELECT *
FROM anotherTable
JOIN "otherTable" ...
returning my_table.id
)
select array_agg(id)
into l_ids
from new_rows;
....
end;
假设我们有一个 plpgsql (PostgreSQL 10.7) 函数,其中有一个查询
INSERT INTO "myTable"
SELECT * FROM "anotherTable"
INNER JOIN "otherTable"
...
因此,此查询将向 myTable 中插入几行。在下一个查询中,我想收集在某些条件下插入的 ID。因此,我的想法是执行以下操作:
INSERT INTO "resultTable" rt
SELECT FROM "myTable"
INNER JOIN ...
WHERE rt."id" >= firstInsertedId;
现在的问题是:如何找到这个 firstInsertedId?
我的解决方案:
select nextval(''"myTable.myTable_id_seq"'') into firstInsertedId;
if firstInsertedId > 1 then
perform setval(''"myTable.myTable_id_seq"'', (firstInsertedId - 1));
end if;
我不太喜欢这个解决方案,因为我认为生成 id,然后返回,然后在插入期间再次生成它对性能没有好处。
想法:
- 正在考虑将 id 插入变量数组然后找到最小值,但没有运气。
- 正在考虑使用 lastval() 函数,但似乎没有' 即使在 MySQL LAST_INSERT_ID() 中非常相似的实现中,它也不适合我。
有什么建议吗?
您可以使用 data modifying common table expression 在一条语句中完成这两项操作。你真的不需要PL/pgSQL。
with new_rows as (
INSERT INTO my_table
SELECT *
FROM anotherTable
JOIN "otherTable" ...
returning my_table.id
)
insert into resulttable (new_id)
select id
from new_rows;
另一种选择是将生成的 ID 存储在数组中。
declare
l_ids integer[];
begin
....
with new_rows as (
INSERT INTO my_table
SELECT *
FROM anotherTable
JOIN "otherTable" ...
returning my_table.id
)
select array_agg(id)
into l_ids
from new_rows;
....
end;