我如何在多个请求中使用返回 id (postgres)
How can i use returning id in multiple requests (postgres)
对于我的任务,我需要添加一个主要条目,然后使用添加记录的 ID 添加一些其他条目。
现在我使用带有“返回 ID”的请求:
with rows as (
insert into "Contact"(name, gender, city, birthdate)
values
('Name', 1, 'City', '2000-02-03')
returning id
)
insert into "Education"(user_id, place, degree, endyear)
select id , 'some_place', 'some_state', 1990 from rows
这样我可以添加一个额外的条目,但我需要多个。如果我尝试执行第二个插入查询 - postgre 失去关系“行”
with rows as (
insert into "Contact"(name, gender, city, birthdate)
values
('Name', 1, 'City', '2000-02-03')
returning id
)
insert into "Education"(user_id, place, degree, endyear)
select id , 'some_place', 'some_state', 1990 from rows
insert into "Status"(user_id, status)
select id , 'val' from rows
ERROR: relation "rows" does not exist
LINE 11: select id , 'val' from rows
^
SQL state: 42P01
Character: 373
有什么办法可以解决这个问题吗?
我建议将所有语句放在 anonymous code block 中。您可以将 RETURNING
用于变量并从那里执行以下插入,例如
DO $$
DECLARE returned_id int;
BEGIN
INSERT INTO contact
(name, gender, city, birthdate) VALUES
('Name', 1, 'City', '2000-02-03')
RETURNING id INTO returned_id;
INSERT INTO education
(user_id, place, degree, endyear) VALUES
(returned_id, 'some_place', 'some_state', '1990-01-01');
INSERT INTO status
(user_id, status) VALUES
(returned_id, 'val');
END;
$$;
演示:db<>fiddle
对于我的任务,我需要添加一个主要条目,然后使用添加记录的 ID 添加一些其他条目。 现在我使用带有“返回 ID”的请求:
with rows as (
insert into "Contact"(name, gender, city, birthdate)
values
('Name', 1, 'City', '2000-02-03')
returning id
)
insert into "Education"(user_id, place, degree, endyear)
select id , 'some_place', 'some_state', 1990 from rows
这样我可以添加一个额外的条目,但我需要多个。如果我尝试执行第二个插入查询 - postgre 失去关系“行”
with rows as (
insert into "Contact"(name, gender, city, birthdate)
values
('Name', 1, 'City', '2000-02-03')
returning id
)
insert into "Education"(user_id, place, degree, endyear)
select id , 'some_place', 'some_state', 1990 from rows
insert into "Status"(user_id, status)
select id , 'val' from rows
ERROR: relation "rows" does not exist
LINE 11: select id , 'val' from rows
^
SQL state: 42P01
Character: 373
有什么办法可以解决这个问题吗?
我建议将所有语句放在 anonymous code block 中。您可以将 RETURNING
用于变量并从那里执行以下插入,例如
DO $$
DECLARE returned_id int;
BEGIN
INSERT INTO contact
(name, gender, city, birthdate) VALUES
('Name', 1, 'City', '2000-02-03')
RETURNING id INTO returned_id;
INSERT INTO education
(user_id, place, degree, endyear) VALUES
(returned_id, 'some_place', 'some_state', '1990-01-01');
INSERT INTO status
(user_id, status) VALUES
(returned_id, 'val');
END;
$$;
演示:db<>fiddle