简体   繁体   English

是否可以在 Postgres 的插入查询中重用单个子查询的标量结果?

[英]Is it possible to reuse scalar result from a single subquery in insert query in Postgres?

I would like to insert several rows of data in Postgres DB table in the same query, but value for one of the columns needs to be calculated using a scalar result from a sub-query and a passed bound parameter.我想在同一个查询中的 Postgres DB 表中插入几行数据,但是需要使用子查询的标量结果和传递的绑定参数来计算其中一列的值。 The calculation is a concatenation of two Postgres arrays.计算是两个 Postgres arrays 的串联。

I was able to do it with a query like this:我可以通过这样的查询来做到这一点:

INSERT INTO my_table (col1, col2, computed_col)
VALUES 
  (
    :col1Val1,
    :col2val1,
    (SELECT some_col FROM some_table WHERE id = :id) || ARRAY[:computed_col1]::bigint[]
  ),
  (
    :col1Val2,
    :col2val2,
    (SELECT some_col FROM some_table WHERE id = :id) || ARRAY[:computed_col2]::bigint[]
  );

CTE works as well, but it looks unnecessary due to the fact that we still need SELECT subquery from CTE "table" for each set of values. CTE 也可以,但看起来没有必要,因为我们仍然需要 CTE“表”中的SELECT子查询来获取每组值。

As you can see SELECT subquery is the same for each set of data to be inserted.如您所见, SELECT子查询对于要插入的每组数据都是相同的。 So is it possible somehow to specify single subquery and reuse the result without repeating SELECT sub-queries, or maybe there is some other way(s) to optimize the query above?那么是否有可能以某种方式指定单个子查询并重用结果而不重复SELECT子查询,或者可能有其他方法来优化上述查询?

And what issues the query can cause from a performance point of view?从性能的角度来看,查询会导致什么问题?

You can do use insert. . . select你可以使用insert. . . select insert. . . select insert. . . select , basically moving the VALUES() into the FROM clause: insert. . . select ,基本上将VALUES()移动到FROM子句中:

INSERT INTO my_table (col1, col2, computed_col)
    SELECT v.col1, v.col2, x.some_col  || v.computed
    FROM (SELECT some_col FROM some_table WHERE id = :id
         ) x CROSS JOIN
         (VALUES (:col1Val1, :col2val1, ARRAY[:computed_col1]::bigint[]),
                 (:col1Val2, :col2val2, ARRAY[:computed_col2]::bigint[])
         ) v(col1, col2, computed);

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

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