简体   繁体   English

如何使用psql客户端执行查询结果?

[英]How do I execute the result of a query using the psql client?

Using the psql client version 8.4.20, I created this select command that generates a bunch of other select commands: 使用psql客户端版本8.4.20,我创建了此select命令,该命令生成了一堆其他的select命令:

mydatabase=# select concat('select count(*) from ', table_schema, '.', table_name, ';') from information_schema.tables where table_name like '%stockindex_alias%';

select count(*) from de_de.merged_stockindex_alias_de_de;
select count(*) from en_us.merged_stockindex_alias_en_us;
select count(*) from es_la.merged_stockindex_alias_es_la;
select count(*) from fr_fr.merged_stockindex_alias_fr_fr;
select count(*) from nl_nl.merged_stockindex_alias_nl_nl;
select count(*) from pt_br.merged_stockindex_alias_pt_br;
select count(*) from zh_hk.merged_stockindex_alias_zh_hk;

I know I can use \\g to store those seven statements into a file, then execute the file with \\i. 我知道我可以使用\\ g将这七个语句存储到文件中,然后使用\\ i执行该文件。

How can I execute the result of the query (those seven statements) in a single command without the intermediate file? 没有中间文件,如何在单个命令中执行查询结果(那七个语句)? I've tried \\set, EXECUTE, searched the web, but can't get it right. 我尝试\\ set,执行,在网上搜索,但无法正确执行。

EDIT: The previous select statements erroneously had the word "table" in them, which I have fixed. 编辑:以前的选择语句错误地在其中包含了“表格”一词,我已对其进行了修复。

I don't know if it works in 8.4; 我不知道它在8.4中是否有效; it works in 9.2. 它适用于9.2。

DO $$
DECLARE
    x text;
BEGIN
    FOR x IN (select concat('select count(*) from ', table_schema, '.', table_name, ';') from information_schema.tables where table_name like '%stockindex_alias%' LOOP
        EXECUTE x;
    END LOOP;
END;
$$;

Basically you create an anonymous function block and execute it. 基本上,您将创建一个匿名功能块并执行它。 Function blocks (or whatever the correct name is) allow for variable declaration and dynamic execution. 功能块(或任何正确的名称)允许变量声明和动态执行。

If you can get by with an approximate count, you can use the system catalogs: 如果可以通过近似计数获得结果,则可以使用系统目录:

SELECT s.nspname AS locale, c.reltuples AS count
FROM pg_class c
JOIN pg_namespace s ON s.oid = c.relnamespace
WHERE c.relname LIKE '%stockindex_alias%';

This will be most accurate immediately after a VACUUM ANALYZE (assuming you are a superuser or own all the affected tables) and gradually reducing in accuracy as the affected tables are modified. 在进行VACUUM ANALYZE (假设您是超级用户或拥有所有受影响的表)之后,这将是最准确的,并随着修改受影响的表而逐渐降低准确性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM