postgresql - 如何使用动态表名进行子查询,其中动态值来自 PostgreSQL 中自己的主查询?
问题描述
我已经形成了这个查询以获得下面提到的所需输出:
select tbl.id, tbl.label, tbl.input_type, tbl.table_name
case when tbl.input_type = 'dropdown' or tbl.input_type = 'searchable-dropdown'
then (select json_agg(opt) from tbl.table_name) as opt) end as options
from mst_config as tbl;
我想要如下输出:
id | label | input_type | table_name | options
----+----------------------------------------------------+---------------------+-------------------------+-----------------------------------------------------------
1 | Gender | dropdown | mst_gender | [{"id":1,"label":"MALE"},
| | | | {"id":2,"label":"FEMALE"}]
2 | SS | dropdown | mst_ss | [{"id":1,"label":"something"},
| | | | {"id":2,"label_en":"something"}]
但是,我在使用时遇到了问题,
select json_agg(opt) from tbl.table_name) as opt
在上面的“tbl.table_name”部分中,我想将它用作动态表名,但它不起作用。
然后,我搜索了很多,发现了类似的东西Execute format('select * from %s', table_name)
,其中 tablename 是动态表名。我什至用 postgres 函数尝试过同样的方法。
但是我在使用 format 方法时又遇到了一个问题。原因是我想使用值需要来自其自己的主查询值的变量,而不是已经在变量中。所以这个也不起作用。
如果有人能帮助我解决这个问题,我将不胜感激。此外,如果有任何其他可能性可以实现此输出,请帮助我。
解决方案
推荐阅读
- npm - Gatsby 网站已构建,但打开 localhost 时出现“UnhandledPromiseRejectionWarning:TypeError:无法读取 parseError 处未定义的属性“split””
- python - 具有自定义功能的数据排序
- javascript - 是否可以使用 jest 将测试导入另一个文件?
- reactjs - 在生产环境中为 React/Express 应用代理 api 请求
- python - Python:使 Rich 不设置字符串样式
- r - R中“字典”数据帧的多种模式和替换,也许是gsub?
- kotlin - 我们如何在 ktor 中模拟 CoroutineDatabase?
- python - 如何传递此错误“ValueError:在 Python 中解包的值太多(预期为 2)?”
- hadoop - Hadoop start-dfs.sh 无法启动节点
- php - 如何调用 .bat 文件而不是将整个路径写入 .exe?