Postgresql 函数,结果集到变量中

Postgresql function, result set into variable

我有程序:

CREATE OR REPLACE FUNCTION func()
RETURNS SETOF bigint AS
$BODY$
DECLARE
    rowsQuantity bigint;
BEGIN
    return query select p.id from product p where...;
    GET DIAGNOSTICS rowsQuantity = ROW_COUNT;
    if(rowsQuantity < 8) then
        return query select p.id from product p where p.id not in (ids from prev query) limit 8 - rowsQuantity;
    end if;
END;
$BODY$
LANGUAGE plpgsql VOLATILE;

我的问题是,如何从第一个查询中获取 id 以在第二个查询中使用它们,或者我可以以某种方式声明变量并将 select 声明到第一个查询中的这个变量 id 中,然后在第二个查询中使用这个变量询问? 我找不到任务的解决方案...请帮助我

我使用 Postgresql 版本 9.3.6

What exactly are you trying to do? The whole function seems overly complicated. This could probably be done with just a single query if you tell us the underlying problem you are trying to solve. Edit your question add some sample data and the expected output based on that data. – a_horse_with_no_name 3 mins ago

我的程序必须 return 8 条记录,第一个查询有很多条件(并且由于这个条件,结果集 ROW COUNT 可以少于 8 个记录)这就是为什么我需要检查第一个查询的 ROW COUNT少于 8 条记录,我必须将记录添加到另一个查询的结果集中,但我需要避免重复,第二个查询必须 return 0...8 行(取决于第一个查询),但没有第一个查询的重复项查询,这就是为什么我需要第一个查询的 id

sounds a simple select distinct p.id from product p where... limit 8; would do the job

不,第二个查询包含我从第一个查询收到的记录(带 ID), 第二个查询中的 DISTINCT 没有帮助

您可以使用临时 table:

begin
    create temp table tt as
        select id 
        from product
        where...
    row_ct = (select count(*) from tt);

    return query select * from tt;

    if row_ct < 8 then
        return query select id 
        from product
        where id not in (select id from tt)
        limit 8 - row_ct;
    end if;
    drop table tt;
end;