SELECT ... INTO postgres CTE 中的变量

SELECT ... INTO a variable within a postgres CTE

我想在 plpgsql 函数中执行此操作

WITH set1 AS (

  select * 
  from table1
  where ... -- reduce table1 to the small working set once for multiple reuse

), query_only_for_select_into AS (

  select id 
  into my_variable_declared_earlier
  from set1 
  where foo = 'bar'
  
)
select my_variable_declared_earlier as my_bar
  , *
from set1
where foo <> 'bar'

但是 Postgres 抛出错误

ERROR:  SELECT ... INTO is not allowed here

我猜这是因为 select ... into 在 CTE 中。但是我在文档或网络上找不到任何关于它的信息。也许我只是搞砸了 select ... into 语法?

SQL 没有变量 - 它们是过程语言的一部分(例如 PL/pgSQL),而不是查询语言。

但我不明白你需要一个的原因:

WITH set1 AS (

  select * 
  from table1
  where ... -- reduce table1 to the small working set once for multiple reuse

), query_only_for_select_into AS (
  select id as my_variable_declared_earlier
  from set1 
  where foo = 'bar'
)
select qs.my_variable_declared_earlier as my_bar,
       *
from set1
  join query_only_for_select_into qs on ...
where foo <> 'bar'

如果您确定query_only_for_select_into只有returns一行,您可以使用:

select qs.my_variable_declared_earlier as my_bar,
       *
from set1
  cross join query_only_for_select_into qs
where foo <> 'bar'

SELECT ... INTO variable 是 PL/pgSQL 语法,您只能将它与顶层 SELECT 一起使用(即 returns 结果。可以这样想: PL/pgSQL 运行 SQL 语句并将结果存储在某处。

但您不需要:只需在主查询的 FROM 子句中包含 query_only_for_select_into,然后您就可以在那里访问它的列。