首页 > 解决方案 > 如何使用动态表名进行子查询,其中动态值来自 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 方法时又遇到了一个问题。原因是我想使用值需要来自其自己的主查询值的变量,而不是已经在变量中。所以这个也不起作用。

如果有人能帮助我解决这个问题,我将不胜感激。此外,如果有任何其他可能性可以实现此输出,请帮助我。

标签: postgresql

解决方案


推荐阅读