1

我有这个复杂的查询,其中用户定义的函数conta_relatos()作为选择语句运行得很好。但是当我尝试使用相同的指令创建视图时它不起作用。Postgres 告诉我“conta_relatos”列有伪类型记录。这个函数,conta_relatos()返回一个记录类型变量。
编辑添加:
返回类型是前面问题中定义的众所周知的复合类型:
Postgres Function End Loop and return Error

以下是查询:

CREATE OR REPLACE VIEW "Sumario" AS 
SELECT "Aspectos"."ID" AS "Aspecto Normativo ID", 
    "Aspectos"."Aspecto" AS "Aspecto Normativo", 
    "Fatores"."ID" AS "Fator Normativo ID", 
    "Fatores"."Fator" AS "Fator Normativo", "Diagnostico"."Vinculo_Final", 
    "Fatores_1"."ID" AS "Fator Determinativo ID", 
    "Fatores_1"."Fator" AS "Fator Determinativo", 
    "Aspectos_1"."ID" AS "Aspecto Determinativo ID", 
    "Aspectos_1"."Aspecto" AS "Aspecto Determinativo", 
    count("Itens"."ID") AS "No Itens", 
    conta_relatos("Fatores"."ID", "Fatores_1"."ID")
FROM  
    "Diagnostico"
JOIN ("Aspectos" "Aspectos_1"
JOIN ("Fontes"
JOIN "Itens" ON "Fontes"."ID" = "Itens"."Fonte"
JOIN ("Fatores" "Fatores_1"
JOIN ("Aspectos"
JOIN ("Vinculos"
JOIN "Fatores" ON "Vinculos"."Fator_Normativo" = "Fatores"."ID") ON "Aspectos"."ID" = "Fatores"."Aspecto" AND "Aspectos"."ID" = "Fatores"."Aspecto") ON "Fatores_1"."ID" = "Vinculos"."Fator_Determinativo") ON "Itens"."ID" = "Vinculos"."Item") ON "Aspectos_1"."ID" = "Fatores_1"."Aspecto") ON "Diagnostico"."ID" = "Vinculos"."Diagnostico_ID"
GROUP BY "Aspectos"."ID", "Aspectos"."Aspecto", "Fatores"."ID", "Fatores"."Fator", "Diagnostico"."Vinculo_Final", "Fatores_1"."ID", "Fatores_1"."Fator", "Aspectos_1"."ID", "Aspectos_1"."Aspecto"
ORDER BY "Aspectos"."ID", "Aspectos_1"."ID", "Fatores"."Fator", "Fatores_1"."Fator";
4

1 回答 1

1

仔细检查:您只需要像这样拆分复合返回类型:

CREATE OR REPLACE VIEW "Sumario" AS 
SELECT ...
 (conta_relatos("Fatores"."ID", "Fatores_1"."ID")).*
FROM ...

手册中有关访问复合类型的详细信息。

顺便说一句:除非您确切知道自己在做什么,否则我建议不要在您的 JOIN 中使用括号。您拥有它的方式是强制执行一个特定的执行计划。很有可能,它不是最好的。


第一种方法误解了错误消息

当您定义一个函数时RETURNS record(我尽可能避免),您必须在每次调用时提供一个列定义列表,例如:

SELECT * FROM conta_relatos(1,2) AS f(col1 int, col2 text, ...)

我在这里引用手册

如果函数已定义为返回记录数据类型,则必须存在别名或关键字 AS,后跟格式为 ( column_name data_type [, ... ] ) 的列定义列表。列定义列表必须与函数返回的列的实际数量和类型相匹配。

干净的解决方案是更改您的函数以返回众所周知的类型而不是匿名记录。有多种方法可以解决这个问题,具体取决于具体情况。如果您在重写函数时遇到问题,请打开另一个问题。

于 2013-02-23T14:45:13.550 回答