大家好,我是postgresql的新手,我有一个具体的问题。我正在尝试创建一个函数,当我运行它到SQL编辑器,一切都很好,我得到了预期的结果。所以这是我运行到sql编辑器的代码:
SELECT email,count(*)
FROM article
GROUP BY email
HAVING count(*)>=2;
但是当我尝试在一个函数上编写它并在sql编辑器上运行该函数时,它只返回结果的第一行。我也点击了选项返回集上的框。我试图创建一些循环为了访问结果但它不起作用。这是功能:
CREATE OR REPLACE FUNCTION public.test()
RETURNS TABLE(a character varying, b integer) AS
$BODY$
DECLARE ema CHARACTER VARYING;
DECLARE coun INTEGER;
BEGIN
CREATE TEMP TABLE exp(email CHARACTER VARYING,counter INTEGER);
SELECT email,count(*) INTO ema,coun
FROM article
GROUP BY email
HAVING count(*)>=2;
INSERT INTO exp(email,counter) VALUES (ema,coun);
RETURN QUERY SELECT DISTINCT * FROM exp;
END;$BODY$
答案 0 :(得分:0)
仅仅因为你要归还一张桌子并不意味着你必须创建一张桌子。尝试更简单:
CREATE OR REPLACE FUNCTION public.test()
RETURNS TABLE(a character varying, b integer) AS
$BODY$
BEGIN
RETURN QUERY
SELECT email a , count(*) b
FROM article
GROUP BY email
HAVING count(*)>=2;
END;
$BODY$
LANGUAGE plpgsql;
请注意,您不需要distinct
,因为您已使用GROUP BY