PostgreSQL:从表中返回选择计数(*);

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4714435/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-20 00:29:59  来源:igfitidea点击:

PostgreSQL: return select count(*) from table;

postgresqlplpgsql

提问by Alexander Farber

please help me with 1 more PL/pgSQLquestion.

请帮我解决另外 1 个PL/pgSQL问题。

I have a PHP-script run as daily cronjob and deleting old records from 1 main table and few further tables referencing its "id" column:

我有一个 PHP 脚本作为每日 cronjob 运行,并从 1 个主表和几个引用其“id”列的其他表中删除旧记录:

create or replace function quincytrack_clean()
        returns integer as $BODY$
        begin
                create temp table old_ids 
                (id varchar(20)) on commit drop;

                insert into old_ids
                select id from quincytrack
                where age(QDATETIME) > interval '30 days';

                delete from hide_id where id in
                (select id from old_ids);

                delete from related_mks where id in
                (select id from old_ids);

                delete from related_cl where id in
                (select id from old_ids);

                delete from related_comment where id in
                (select id from old_ids);

                delete from quincytrack where id in
                (select id from old_ids);

                return select count(*) from old_ids;
        end;
$BODY$ language plpgsql;

And here is how I call it from the PHP script:

这是我从 PHP 脚本调用它的方式:

$sth = $pg->prepare('select quincytrack_clean()');
$sth->execute();
if ($row = $sth->fetch(PDO::FETCH_ASSOC))
        printf("removed %u old rows\n", $row['count']);

Why do I get the following error?

为什么会出现以下错误?

SQLSTATE[42601]: Syntax error: 7 
ERROR:  syntax error at or near "select" at character 9
QUERY:  SELECT  select count(*) from old_ids
CONTEXT:  SQL statement in PL/PgSQL function
"quincytrack_clean" near line 23

Thank you! Alex

谢谢!亚历克斯

回答by Quassnoi

RETURN (select count(*) from old_ids);