function - 查询可变数量的模式
问题描述
这似乎是很常见的问题,但这是我第一次面对它并且找不到合适的解决方案。
我需要创建一个函数来动态引用模式,它们是用一种模式创建的,每个模式都有相同的表(名称和列)。以前,只需要计算与模式名称关联的不同表中的记录。
当需要查找所有模式时,我打算在 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
解决方案
推荐阅读
- c# - 在 C# Entity Framework 中的 sql 连接字符串中使用端口:不支持关键字:“端口”
- python - 我安装了pwndbg,但是出现这样的错误。如何解决这个错误?
- php - laravel 未定义变量:fetchdata(查看:C:\xampp\htdocs\A3Solution\resources\views\A3View\view.blade.php)
- python - 从 cmd 运行时出现 Python setup.py 错误
- google-apps-script - 缺少标识符 rc 的库
- python - 在 GUI 中输入并在 IDLE 中打印(python)
- makefile - (GNU) Make 如何处理多个匹配目标?
- windows - TSaveDialog 改变文件名的大小写
- javascript - 将 Ag-grid 与嵌套对象的对象一起使用
- go - 如何在 go-elasticsearch 中使用 gin?