如何在postgresql中使用多个RETURN QUERY限制结果集

时间:2015-03-30 15:02:38

标签: sql postgresql sql-limit set-returning-functions

我有多个RETURN QUERY语句的功能。最后,我想只获得N个随机记录。如果我在结尾处将LIMIT max_size设置为每个RETURN QUERY语句,我将max_size *计算RETURN QUERY次。

我的函数的简短版本:

CREATE OR REPLACE FUNCTION android_getproposedsongs_test(
                                          IN puserid character varying, max_size int)
    RETURNS TABLE(sid uuid, method text) AS
$BODY$
DECLARE
    songCount int;
BEGIN

RETURN QUERY 
    SELECT trackid as sid, lower('popular') as method
    FROM ratingrecord
    WHERE trackid NOT IN (
       SELECT trackid FROM ratingrecord WHERE userid = puserid)
    AND ratingrecord.rating > 0
    GROUP BY trackid
    HAVING SUM(rating) > 0
    ORDER BY SUM(rating) DESC
    LIMIT max_size;

CREATE TEMP TABLE recommended ON COMMIT DROP 
AS
SELECT trackid, lower('recommended')
FROM ratingrecord finalRate
    INNER JOIN 
    (
        SELECT otherRate.userid AS otherUserId
             , SUM(myRate.rating * otherRate.rating) as SumRating 
        FROM ratingrecord AS myRate
        INNER JOIN ratingrecord AS otherRate 
        ON myRate.trackid = otherRate.trackid
        WHERE myRate.userid = puserid AND myRate.userid != otherRate.userid         
        GROUP BY otherRate.userid
        HAVING SUM(myRate.rating * otherRate.rating) > 0
    )  AS userRelations 
    ON finalRate.userid = userRelations.otherUserId
WHERE finalRate.trackid NOT IN (SELECT trackid FROM ratingrecord WHERE userid = puserid)
GROUP BY finalRate.trackid
HAVING SUM(finalRate.rating * userRelations.SumRating) > 0
ORDER BY SUM(finalRate.rating * userRelations.SumRating) DESC
LIMIT max_size;

RETURN QUERY SELECT * FROM recommended;

-- another RETURN QUERY statements

END;    
$BODY$ 
LANGUAGE plpgsql VOLATILE;

我想在结果集中使用ORDER BY random() LIMIT max_size之类的东西,但不知道放在哪里。

1 个答案:

答案 0 :(得分:0)

使用UNION ALL组合纯SQL中的所有子查询,并在结尾添加ORDER BY random() LIMIT n一次。

或者你必须跟踪自己在plpgsql中返回的行数,如下所示:

CREATE OR REPLACE FUNCTION android_getproposedsongs_test(puserid varchar, max_size int)
  RETURNS TABLE(sid uuid, method text) AS
$func$
DECLARE
   song_count int;  -- I'd rather not use spurious capitalisation
   running_ct int := 0;
   ct         int;
BEGIN

RETURN QUERY SELECT ... LIMIT max_size; -- apply to each individual query!

GET DIAGNOSTICS ct = ROW_COUNT;
running_ct := running_ct + ct;
IF running_ct >= max_size THEN
   RETURN;
END IF;

RETURN QUERY SELECT ... LIMIT max_size;

GET DIAGNOSTICS ct = ROW_COUNT;
running_ct := running_ct + ct;
IF running_ct >= max_size THEN
   RETURN;
END IF;

-- another RETURN QUERY statements

END 
$func$ LANGUAGE plpgsql VOLATILE;

相关:

,这只返回第一个 N行,而不是随机选择。要实现 ,请无限制地返回 所有 符合条件的行,并在下一步中应用ORDER BY random() LIMIT n

SELECT *
FROM   android_getproposedsongs_test('foo', 3)
ORDER  BY random() LIMIT 123;

你必须意识到获得随机行可能会花费更多 ,因为必须首先识别所有(可能很多)候选者。返回第一个N行可能 更便宜。