PostgreSQL 最后插入的 ID 不是自动递增打字稿续集
PostgreSQL last inserted ID not auto-increment typescript sequelize
用户(
身份证号 ,
名称:字符串 pk)
如何获取最大的最新id插入新id? objective 是取之前的id 加一个值,但是id 不是自增的。我正在考虑进行查询以获取最新的 id 但我希望可能有其他优化建议
谢谢
你可以做你想做的。但仅仅因为你可以做某事并不意味着你应该做。我再说一遍,您应该使用序列号或标识。 @Stefanov.sm 在 MVCC 环境中是正确的,这是一个非常糟糕的主意;因为它是虚拟保证,所以您有时会得到一份副本。
实现这一点的一种方法是编写一个函数来执行插入。这个函数得到 MAX(ID) + 一个增量。它还处理重复错误并在需要时重试插入。
create or replace
function establish_user (user_name_in text )
returns integer
language plpgsql
as $$
declare
k_id_inc constant integer := 1;
l_id integer;
l_inserted boolean = false;
begin
select coalesce(max(id) + k_id_inc)
into l_id
from users;
while not l_inserted
loop
begin
insert into users (id, name)
values (l_id, user_name_in);
l_inserted = true;
exception
when others then
if sqlstate != '23505'
or sqlerrm not like '%users_id_uk%'
then
raise;
else
l_id = l_id + 1;
end if;
end;
end loop;
return l_id;
end;
$$;
请参阅此处 Demo。
用户( 身份证号 , 名称:字符串 pk)
如何获取最大的最新id插入新id? objective 是取之前的id 加一个值,但是id 不是自增的。我正在考虑进行查询以获取最新的 id 但我希望可能有其他优化建议
谢谢
你可以做你想做的。但仅仅因为你可以做某事并不意味着你应该做。我再说一遍,您应该使用序列号或标识。 @Stefanov.sm 在 MVCC 环境中是正确的,这是一个非常糟糕的主意;因为它是虚拟保证,所以您有时会得到一份副本。
实现这一点的一种方法是编写一个函数来执行插入。这个函数得到 MAX(ID) + 一个增量。它还处理重复错误并在需要时重试插入。
create or replace
function establish_user (user_name_in text )
returns integer
language plpgsql
as $$
declare
k_id_inc constant integer := 1;
l_id integer;
l_inserted boolean = false;
begin
select coalesce(max(id) + k_id_inc)
into l_id
from users;
while not l_inserted
loop
begin
insert into users (id, name)
values (l_id, user_name_in);
l_inserted = true;
exception
when others then
if sqlstate != '23505'
or sqlerrm not like '%users_id_uk%'
then
raise;
else
l_id = l_id + 1;
end if;
end;
end loop;
return l_id;
end;
$$;
请参阅此处 Demo。