sql - 跨不同模式的 Postgres SQL 查询
问题描述
我们有多个模式,我想跨模式运行一个简单的计数查询,例如:
SELECT COUNT(col_x) FROM schema1.table WHENRE col_x IS NOT NULL
我看到我能够通过以下方式获得所有模式:
SELECT schema_name FROM information_schema.schemata
所以通过使用:
set search_path to schema1;
SELECT COUNT(col_x)
FROM table
WHERE col_x is not NULL;
我能够运行 schema1 的查询
问题是 - 是否可以循环运行并将模式名称用作 search_path 的参数并跨所有模式运行查询?或任何其他有效的方法?
解决方案
为此,您将需要一些plpgsql
动态 SQL。这是一个用于说明的匿名块:
do language plpgsql
$$
declare
v_schema_name text;
table_row_count bigint;
sysSchema text[] := array['pg_toast','pg_temp_1','pg_toast_temp_1','pg_catalog','public','information_schema'];
-- other declarations here
begin
for v_schema_name in SELECT schema_name FROM information_schema.schemata WHERE (schema_name != ALL(sysSchema)) loop
begin
execute format('select count(col_x) from %I.t_table', v_schema_name)
into table_row_count;
raise notice 'Schema % count %', v_schema_name, table_row_count;
exception when others then null; -- t_table may not exists in some schemata
end
-- other statements here
end loop;
end;
$$;
顺便说一句WHERE col_x is not NULL
是多余的。
推荐阅读
- netbeans - 不使用 nb-javac 时禁用 NetBeans 12.0 中的“安装”消息
- javascript - 创建带有 json 响应的 html 表
- docker - 为什么 docker-compose 在使用“-p”标志运行时会启动不同的图像
- reactjs - Vimeo API:无法上传视频 - “未提供用户凭据。” (8003)
- vb.net - 在 vb.net 中有没有更快的方法来解决这个问题?
- c# - 是否有任何伪造的方法可以根据 C# 中的输入字符为我提供美国的城市名称?
- python - VSCode MyPy 错误:“ioctl”具有不兼容的类型“my_struct”;预期“联合[int,str]”
- elasticsearch - Elasticsearch - 对象类型,搜索嵌套元素
- javascript - toString 导致箭头函数内部出错
- python-3.x - 从 pythonscript 导入变量 --> 解决导致的 TypeError