首页 > 解决方案 > 查询可变数量的模式

问题描述

这似乎是很常见的问题,但这是我第一次面对它并且找不到合适的解决方案。

我需要创建一个函数来动态引用模式,它们是用一种模式创建的,每个模式都有相同的表(名称和列)。以前,只需要计算与模式名称关联的不同表中的记录。

当需要查找所有模式时,我打算在 FROM 子句上使用这个函数。

输出示例:

  Client  |UserName|           #post                                        |             #notification  
  schema1 | user1  |count(id) from schema1.post where post.user_id = user.id| count(id) from schema1.notif  where notif.user_id = user.id
  schema1 | user2  |count(id) from schema1.post where post.user_id = user.id| count(id) from schema1.notif  where notif.user_id = user.id
  schema2 | user3  |count(id) from schema2.post where post.user_id = user.id| count(id) from schema2.notif  where notif.user_id = user.id

到目前为止,我的策略是创建一个动态函数来设置 shchema、表和列。

CREATE OR REPLACE FUNCTION tenant( schemaName varchar, tableName varchar, attr varchar) 
RETURNS "record" AS $BODY$
DECLARE
  temp record;
BEGIN
  EXECUTE 
  'SELECT ' || attr || 
  'FROM ' || schemaName || '.' || tableName  into temp;

  RETURN temp;
END;
$BODY$
  LANGUAGE 'plpgsql' VOLATILE;

但是我在执行 ERROR: could not determine polymorphic type because input has type "unknown" SQL state: 42804 时收到此错误消息

另一种方法是创建一个返回引用表的函数。但是列和数据类型应该是动态的,使用如下:

SELECT c.schema, u.name, 
(SELECT COUNT(post.id) from func(c.schema, 'post') AS count_post),
(SELECT COUNT(notification.id) from func(c.schema, notification') AS count_notification)   
FROM _global.customer AS c,  
_global.user AS u WHERE u.customer_id = c.id 

标签: functionschemaplpgsqlpostgresql-9.6

解决方案


推荐阅读