2017-05-19 51 views
0

是否有可能重寫此plpgsql過程以避免json.get_user_notifications被調用兩次?如何重寫postgresql過程以避免第二次調用

CREATE OR REPLACE FUNCTION json.rowset_notifications(arg1 integer, arg2 integer, arg3 integer) 
    RETURNS SETOF json.notification AS 
$BODY$ 
DECLARE 
    pmax_limit boolean; 
BEGIN 
    pmax_limit := (SELECT COUNT(*) > 200 FROM json.get_user_notifications($1, $2, $3)); 
    IF pmax_limit THEN 
    RETURN QUERY SELECT n.* FROM json.get_compressed_user_notifications($1, $2, $3) n; 
    ELSE 
    RETURN QUERY SELECT n.* FROM json.get_user_notifications($1, $2, $3) n; 
    END IF; 
END 
$BODY$ 
    LANGUAGE plpgsql STABLE 
    COST 100 
    ROWS 200; 

類似的東西(當然它不工作):

WITH 
    notifications AS (SELECT n.* FROM json.get_user_notifications($1, $2, $3) n LIMIT 201) 
SELECT CASE 
    WHEN COUNT(*) > 200 THEN 
     RETURN QUERY SELECT n.* FROM json.get_compressed_user_notifications($1, $2, $3) n; 
    ELSE 
     RETURN QUERY SELECT n.* FROM notifications n; 
    END 
FROM notifications; 

回答

0

也許你尋找一個:

WITH notifications AS (
    SELECT n.* 
     FROM json.get_user_notifications($1, $2, $3) n 
     LIMIT 201 
) 
SELECT * 
    FROM notifications 
WHERE (SELECT COUNT(*) <= 200 FROM notifications) 
UNION 
SELECT * 
    FROM json.get_compressed_user_notifications($1, $2, $3) 
WHERE (SELECT COUNT(*) > 200 FROM notifications) 

;

0

當然,運行其他查詢這樣

SELECT n.* 
FROM json.get_user_notifications($1, $2, $3) AS n 
WHERE (SELECT count(*)>200 FROM json.get_user_notifications) 

您可能必須要明確。如果返回,那麼您可以返回結果集json.notification。如果它不返回,那麼你知道你需要返回壓縮結果集。

+0

看來,這個例子不起作用: SELECT ID FROM generate_series(1,300)ID GROUP BY ID HAVING COUNT(*)<= 200 – Fr1ar

+0

@ Fr1ar似乎爲我工作,你試圖看看'count(*)<= 200'。在你的查詢中,generate_series正在生成'[1,300]'在該範圍內生成的值都不會生成兩次。它們全部生成一次,因此在分組之後所有的「count(*)」都是一個.. –

+0

好吧,我明白了。不幸的是,我忘記提到,在我的情況下,所有記錄都是獨一無二的我只需要知道count是否大於200,那麼我就返回壓縮集。 – Fr1ar