【问题标题】:Postgresql function for nested selects within an insert用于插入中嵌套选择的 Postgresql 函数
【发布时间】:2018-02-08 12:46:09
【问题描述】:

我创建了一个函数 abcd_insert(),它将数据插入到表 abcd 中,该表有 8 列。函数内的代码如下所示:

BEGIN  
 INSERT INTO abcd

 VALUES 
      (
    x                 ,
    y                 ,
    select sum(count) from (select count(*) from a where a1 = x and a2 = y and a3 = 1 union all select count(*) from b where b1 = x and b2 = y and b3 = 1 ) as n1,
    select sum(count) from (select count(*) from a where a1 = x and a2 = y and a2 = 2 union all select count(*) from b where b1 = x and b2 = y and b3 = 2 ) as n2 ,
    select sum(count) from (select count(*) from a where a1 = x and a2 = y and a2 = 3 union all select count(*) from b where b1 = x and b2 = y and b3 = 3 ) as n3 ,
    select sum(count) from (select count(*) from a where a1 = x and a2 = y and a2 = 4 union all select count(*) from b where b1 = x and b2 = y and b3 = 4 ) as n4 ,
    select sum(count) from (select count(*) from a where a1 = x and a2 = y and a2 = 5 union all select count(*) from b where b1 = x and b2 = y and b3 = 5 ) as n5 ,
    SELECT sum(q1) from
    (SELECT CASE WHEN COUNT(1) > 0 THEN 1 ELSE 0 END as q1 FROM p1 where p11 = x and p12 = y union all
    SELECT CASE WHEN COUNT(1) > 0 THEN 1 ELSE 0 END as q1 FROM p2 where p21 = x and p22 = y )  as q1
  ); 
END; 

'x' 和 'y' 是我的输入参数,它们的值将被传递给函数 abcd_insert()。 a,b,p1 和 p2 是同一模式中的表。 当我在运行时将“x”和“y”传递给函数时,它会引发错误。 有人可以告诉我我在这里做错了什么。

【问题讨论】:

  • 这里有 2 个子查询。一个是缺少别名。

标签: sql postgresql function procedural


【解决方案1】:

您需要命名列,而不仅仅是派生表:

SELECT SUM(foo) as foo
FROM ((SELECT CASE WHEN COUNT(1) > 0 THEN 1 ELSE 0 END) as foo FROM a.a1 where p1=100) UNION ALL
      . . .
     ) x

【讨论】:

  • 反之亦然:OP 已命名列,但未命名派生表。 x 是他们需要的部分(as bar 可能是一个更清晰的例子)。
猜你喜欢
  • 2018-09-23
  • 2011-10-23
  • 1970-01-01
  • 1970-01-01
  • 2014-02-18
  • 1970-01-01
  • 2020-11-24
  • 2011-08-30
相关资源
最近更新 更多