【问题标题】:PostgreSQL: subquery must return one columnPostgreSQL:子查询必须返回一列
【发布时间】:2016-11-01 12:34:22
【问题描述】:

看起来很明显的错误,仍然看不到机会找到它。我在这个函数中做了本地化错误:

CREATE OR REPLACE FUNCTION findRecipientsByQuestion(questionId BIGINT)
RETURNS SETOF BIGINT AS $$
DECLARE
  question questionObject;  

  BEGIN
    question := (
      SELECT "a"."id", "a"."body", "a"."author_id", "a"."category_id", "a"."urgent", "a"."created_at", "a"."locale_id", "a"."lat", "a"."lng", "a"."radius" 
      FROM "question" "a" 
      WHERE "a"."id"=questionId 
      LIMIT 1
    );


    RETURN QUERY SELECT "a"."id" 
    FROM "user" "a" INNER JOIN "notifications" "b" ON ("a"."id"="b"."user_id")
    WHERE ("b"."category_id"=question.category_id OR "b"."urgent") AND 
        isGeoMatch("a"."lat", "a"."lng", "a"."radius", question.lat, question.lng, question.radius);
  END 
  $$LANGUAGE plpgsql;

使用这种类型的:

CREATE TYPE questionObject AS (
  id BIGINT,
  body VARCHAR,
  author_id BIGINT,
  category_id BIGINT,
  urgent BOOLEAN,
  created_at TIMESTAMP,
  locale_id BIGINT,
  lat DOUBLE PRECISION,
  lng DOUBLE PRECISION,
  radius INTEGER
);

我在运行时遇到了这个错误:

Error: subquery must return only one column

【问题讨论】:

  • 事实上,您有两个查询。您是否分别尝试过?哪个触发了错误?
  • 好消息让我试试
  • 好吧,问题出在第一个查询中......
  • 你要么select into@Juan 回答要么question := (select ("a"."id", ...) from ...)
  • 顺便说一句,除非变量名称中有大写和空格,否则不需要使用这么多 ""。所以建议不要使用大写或空格来保持代码简单。

标签: postgresql plpgsql


【解决方案1】:

我会摆脱所有的复杂性,把它变成普通的 sql:

create or replace function findrecipientsbyquestion (
    _questionid bigint
) returns setof bigint as $$

    select a.id 
    from
        user a
        inner join
        notifications b on a.id = b.user_id
        inner join (
            select categoty_id, lat, lng, radius 
            from question
            where id = _questionid 
            limit 1
        ) q on q.category_id = b.category_id or b.urgent
    where isgeomatch(a.lat, a.lng, a.radius, q.lat, q.lng, q.radius);

$$ language sql;

【讨论】:

  • 感谢您的建议,这绝对比我的解决方案更干净
【解决方案2】:

我的类型

CREATE TYPE map.get_near_link AS
   (link_id integer,
    distance integer,
    direction integer,
    geom public.geometry(4));

我愿意

sRow map.get_near_link;

SELECT i.Link_ID, i.Distance, i.Direction, i.geom into sRow 
FROM 
    index_query i;

【讨论】:

  • 谢谢,这完成了工作;)再次感谢您的“”建议。
猜你喜欢
  • 1970-01-01
  • 2019-12-02
  • 2013-11-08
  • 1970-01-01
  • 2022-01-01
  • 2019-11-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多