Postgres 使用 WITH 子句插入 select
Postgres Insert select using WITH clause
我正在尝试使用 INSERT ... SELECT ...
创建一些条目,但还需要使用第一个 INSERT
操作的主键作为辅助操作的一部分:
WITH dogEntries as (INSERT INTO dog (id, another_id, name, date_created)
SELECT public.uuid_generate_v4(), 'efd55343', name, date_created
FROM dog WHERE owner_id = '8921571' RETURNING id as dog_uuid)
INSERT INTO dog_toys (dog_id, bed_id, status)
SELECT (SELECT dog_uuid FROM dogEntries), bed_id, status FROM dog_toys
WHERE dog_id IN(SELECT dog_id FROM dogs WHERE another_id = '21571');
public.uuid_generate_v4() 将生成 id 列。
但我收到一个错误,不确定但我猜是因为 WITH dogEntries
当然会返回多个条目。
错误:
[21000] ERROR: more than one row returned by a subquery used as an
expression
是否有返回和遍历 dog table 插入行的替代方法,或者关于如何遍历 WITH dogEntries
语句中的每个条目的提示?
(SELECT dog_uuid FROM dogEntries)
在第二个 INSERT
的 SELECT
列表中导致错误消息,因为它 returns 多行。它可能是这样工作的:
WITH dogentries AS (
INSERT INTO dog (id, another_id, name, date_created)
SELECT public.uuid_generate_v4(), 'efd55343' name, date_created
FROM dog
WHERE owner_id = 8921571
RETURNING id AS dog_uuid
)
INSERT INTO dog_toys (dog_id, bed_id, status)
SELECT de.dog_uuid, dt.bed_id, dt.status
FROM dogentries de
JOIN dog d ON d.another_id = 21571
JOIN dog_toys dt USING (dog_id);
这是在黑暗中拍摄的。 objective 不完全清楚,table 定义未公开。
我正在尝试使用 INSERT ... SELECT ...
创建一些条目,但还需要使用第一个 INSERT
操作的主键作为辅助操作的一部分:
WITH dogEntries as (INSERT INTO dog (id, another_id, name, date_created)
SELECT public.uuid_generate_v4(), 'efd55343', name, date_created
FROM dog WHERE owner_id = '8921571' RETURNING id as dog_uuid)
INSERT INTO dog_toys (dog_id, bed_id, status)
SELECT (SELECT dog_uuid FROM dogEntries), bed_id, status FROM dog_toys
WHERE dog_id IN(SELECT dog_id FROM dogs WHERE another_id = '21571');
public.uuid_generate_v4() 将生成 id 列。
但我收到一个错误,不确定但我猜是因为 WITH dogEntries
当然会返回多个条目。
错误:
[21000] ERROR: more than one row returned by a subquery used as an expression
是否有返回和遍历 dog table 插入行的替代方法,或者关于如何遍历 WITH dogEntries
语句中的每个条目的提示?
(SELECT dog_uuid FROM dogEntries)
在第二个 INSERT
的 SELECT
列表中导致错误消息,因为它 returns 多行。它可能是这样工作的:
WITH dogentries AS (
INSERT INTO dog (id, another_id, name, date_created)
SELECT public.uuid_generate_v4(), 'efd55343' name, date_created
FROM dog
WHERE owner_id = 8921571
RETURNING id AS dog_uuid
)
INSERT INTO dog_toys (dog_id, bed_id, status)
SELECT de.dog_uuid, dt.bed_id, dt.status
FROM dogentries de
JOIN dog d ON d.another_id = 21571
JOIN dog_toys dt USING (dog_id);
这是在黑暗中拍摄的。 objective 不完全清楚,table 定义未公开。