假设我们有一个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;

现在的问题是:如何找到第一个插入者?
我的解决方案:
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;

关于sql - 如何从INSERT查询中获取第一个ID,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57196146/

10-14 15:16
查看更多