[英]function returns one row from QUERY postgresql
Hello to everyone i am new to postgresql and I have a specific question. 大家好,我是Postgresql的新手,我有一个特定的问题。 I am trying to create a function which when I run it to sql editor, everything is fine and i get the expected result.
我正在尝试创建一个函数,当我将其运行到sql编辑器时,一切都很好,并且我得到了预期的结果。 So this is the code that i run to sql editor:
这是我运行到sql编辑器的代码:
SELECT email,count(*)
FROM article
GROUP BY email
HAVING count(*)>=2;
But when i try to write this on a function and run the function on sql editor, it returns me only the first row of the result.Also i have clicked in the box on option Return set .I tried to create some loops in order to access the results but it didn't work. 但是,当我尝试在函数上编写此代码并在sql编辑器上运行该函数时,它仅返回结果的第一行。我也单击了Return set选项中的框。我试图创建一些循环以访问结果,但是没有用。 Here is the function :
这是函数:
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$
Just because you are returning a table doesnt mean you have to create one. 仅仅因为您要返回一个表并不意味着您必须创建一个表。 Try it more simple:
尝试更简单:
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;
Note you dont need distinct
because you are already using GROUP BY
请注意,您不需要
distinct
因为您已经在使用GROUP BY
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.