如何计算数据库中表的所有行和列?

时间:2019-09-06 11:05:35

标签: postgresql

我想显示表的所有列并计算数据库中所有表的行。

我正在使用此函数,该函数为我提供了表的名称和表的行数

CREATE OR REPLACE FUNCTION count_em_all () RETURNS SETOF table_count  AS '
DECLARE 
    the_count RECORD; 
    t_name RECORD; 
    t_column RECORD;
    r table_count%ROWTYPE; 

BEGIN
    FOR t_name IN 
        SELECT *
        FROM information_schema.tables
        where table_schema !=''pg_catalog''
          and table_schema !=''information_schema''
        ORDER BY 1,2
        LOOP
            FOR the_count IN EXECUTE ''SELECT COUNT(*) AS "count" FROM '' || t_name.table_schema||''.''||t_name.table_name
            LOOP 
            END LOOP; 

            r.table_schema := t_name.table_schema;
            r.table_name := t_name.table_name; 
            r.num_rows := the_count.count; 
            RETURN NEXT r; 
        END LOOP; 
        RETURN; 
END;
' LANGUAGE plpgsql; 

但是我还需要表列名

select table_schema, 
       table_name, column_name
       (xpath('/row/cnt/text()', xml_count))[1]::text::int as row_count
from (
  select table_name, table_schema, 
         query_to_xml(format('select count(*) as cnt from %I.%I', table_schema, table_name), false, true, '') as xml_count
  from information_schema.tables
  where table_schema = 'public' --<< change here for the schema you want
) t

Error:

 syntax error at or near "["
LINE 3:        (xpath('/row/cnt/text()', xml_count))[1]::text::int a...

1 个答案:

答案 0 :(得分:0)

您需要将查询结果连接到information_schema.columns并将列聚合为一个字符串。在派生表(也称为“子查询”)中进行聚合更容易:

select t.table_schema, 
       t.table_name, 
       (xpath('/row/cnt/text()', xml_count))[1]::text::int as row_count,
       c.columns
from (
  select table_name, table_schema, 
         query_to_xml(format('select count(*) as cnt from %I.%I', table_schema, table_name), false, true, '') as xml_count
  from information_schema.tables
  where table_schema = 'public' --<< change here for the schema you want
) t
  join (
    select col.table_schema, col.table_name, 
           string_agg(col.column_name::text, ',' order by col.ordinal_position) as columns
    from information_schema.columns col
    group by col.table_schema, col.table_name
  ) c on t.table_schema = c.table_schema
     and t.table_name = c.table_name;