简体   繁体   English

如何结合这两个Postgresql查询?

[英]How to combine these two Postgresql queries?

I want to insert into a first table, then update a second table with the returned (DB generated) UUID of the inserted row before finally returning the result of the insert. 我想插入到第一个表中,然后在最终返回插入结果之前,使用返回的(由数据库生成的)插入行的UUID更新第二个表。

The insert query looks like this: 插入查询如下所示:

INSERT INTO public.organisations ("name")
VALUES('StackOverflow')
RETURNING *

This will return a row with name, data and id. 这将返回包含名称,数据和ID的行。 Data is an empty JSON and can be ignored, id is the UUID used below. 数据是一个空JSON,可以忽略,id是下面使用的UUID。

The update query looks like this, with <orgId> indicating the UUID generated and returned by the above insert and <userId> indicating a value passed in from code: 更新查询如下所示,其中<orgId>表示由上述插入生成并返回的UUID,而<userId>表示从代码传入的值:

UPDATE public.users
SET id_organisation = <orgID>, last_modified_by = <userID>
WHERE id = <userID>;

Both of these queries work but I do not know how to string them together and return the output of the first query. 这两个查询都有效,但是我不知道如何将它们串在一起并返回第一个查询的输出。

Is it possible to do this or would I be better just running two queries? 是否可以执行此操作?还是只运行两个查询会更好?

Use CTEs: 使用CTE:

with i as (
      INSERT INTO public.organisations ("name")
          VALUES('StackOverflow')
          RETURNING *
     )
UPDATE public.users
    SET id_organisation = (SELECT i.id FROM i LIMIT 1),        last_modified_by = <userID>
    WHERE id=<userID>;

Note that this uses a subquery with LIMIT -- this guarantees that at most one row is returned. 请注意,这使用带有LIMIT的子查询-这样可以保证最多返回一行。

Here is a db<>fiddle illustrating that the syntax works. 是一个db <> fiddle,说明了语法的工作原理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM