首页 > 解决方案 > 当函数不返回任何内容时,postgres 选择不返回任何记录

问题描述

我很难说出这个问题——

我有这个返回记录的简单选择语句

SELECT q.qid,q.question,depth,active  
FROM q 
JOIN qp ON q.qid = qp.descendant where qid=723
order by depth

这正确返回了它之后的 1 条记录

但是,当我在 select 语句中包含一个函数时,它不再返回记录,我不确定为什么会这样。

SELECT q.qid,q.question,depth,active,(getprevquestiontemp(qid)).qid parent  
FROM q 
JOIN qp ON q.qid = qp.descendant where qid=723
order by depth

这是功能

CREATE OR REPLACE FUNCTION getprevquestiontemp(cur_qid integer)
  RETURNS SETOF q AS
$BODY$ 
SELECT q.* FROM q 
JOIN qp ON q.qid = qp.ancestor WHERE qp.descendant = cur_qid
AND depth = 1;
$BODY$
  LANGUAGE sql VOLATILE
  COST 100
  ROWS 1000;

标签: postgresql

解决方案


不要在 SELECT 列表中使用该函数,像使用外连接的表一样使用它:

SELECT q.qid, q.question, depth, active, g.qid parent  
FROM q 
  JOIN qp ON q.qid = qp.descendant 
  LEFT JOIN getprevquestiontemp(qid) as g(qid) ON true
where qid=723
order by depth

不相关,但是:如果您将函数声明为stable优化器,则可以 [内联] https://wiki.postgresql.org/wiki/Inlining_of_SQL_functions()该函数可能会带来更好的性能


推荐阅读