【问题标题】:How can I count records in multiple tables having same column for where clause is pgsql如何计算多个表中具有相同列的 where 子句是 pgsql 的记录
【发布时间】:2016-06-14 09:14:56
【问题描述】:

我正在为我的数据库使用 postgre sql 和 phpPgAdmin。

我有一个表,我在其中添加了一些表名,例如:

table_lsts

id 名称表名

11 abbc table1

22 xyyz table2

33张桌子3

现在在 table1、table2、table3 中,我有多个记录,它们有一个名为 vpvc_id 的公共列。

我的问题是我必须编写一个查询,首先从 table_lsts 获取所有表名。

然后计算那些表中的记录,其中 vpvc_id in (some ids here) etc

有人可以帮忙吗?

【问题讨论】:

    标签: php postgresql


    【解决方案1】:

    试试这个功能:

    CREATE OR REPLACE FUNCTION count_records (ids_lst character varying)
     RETURNS integer AS
    $BODY$declare 
     query character varying;
     result integer;
     BEGIN 
       -- First query that create a dynamic query on all tables of table_lsts
        select into query 'select count(*) from (' || String_agg('select vpc_id from '||tablename,' UNION ALL ') || ') a where vpc_id in ('||ids_lst||')' from table_lsts ;
     ---execute dynamic query
     execute query  into result;
    return result;
    END;$BODY$
    LANGUAGE plpgsql VOLATILE
    

    并像这样使用它:

     select count_records('2,5')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-20
      • 1970-01-01
      • 2012-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多