2015-07-21 95 views
0

我想編寫一個查詢來計算數據庫中的每個對象。我知道你可以查詢統計信息,但是我想知道如何編寫這種一般類型的查詢,以防我需要再次執行。從初始查詢的結果中執行多個計數查詢的總和

我有這個疑問,這在DB給每個表名的結果:

SELECT table_name 
FROM information_schema.tables 
WHERE table_schema='public' 
AND table_type='BASE TABLE' 

結果是這個樣子:

table_name 
---------- 
queue_classic_jobs 
activities 
attachments 
comments 
csv_files 

我想要做的每一個count(*)每個結果行的表格:

table_name  |  row_count 
---------------------------------- 
queue_classic_jobs    6 
activities      2 
attachments      4 
comments       8 
csv_files      10 

然後求和row_count列。我的查詢應該是什麼樣子?

回答

1

使用plpgsql EXECUTE命令。

您有兩種選擇。首先是與臨時表的匿名代碼塊保存結果:

CREATE TEMP TABLE IF NOT EXISTS results(table_name text, row_count bigint); 
TRUNCATE results; 
DO $$ 
DECLARE 
    tname text; 
BEGIN 
    FOR tname IN 
     SELECT table_name 
     FROM information_schema.tables 
     WHERE table_schema='public' 
     AND table_type='BASE TABLE' 
    LOOP 
     EXECUTE format($fmt$ 
      INSERT INTO results 
      SELECT '%s', count(*) from %s 
      $fmt$, tname, tname); 
    END LOOP; 
END $$; 

SELECT * FROM results 
UNION ALL 
SELECT 'TOTAL', sum(row_count) FROM results; 

第二個選項是一個PLPGSQL功能:

CREATE OR REPLACE FUNCTION show_row_count() 
RETURNS TABLE (table_name text, row_count bigint) 
LANGUAGE plpgsql 
AS $$ 
DECLARE 
    tname text; 
BEGIN 
    FOR tname IN 
     SELECT i.table_name 
     FROM information_schema.tables i 
     WHERE table_schema='public' 
     AND table_type='BASE TABLE' 
    LOOP 
     RETURN QUERY EXECUTE format($fmt$ 
      SELECT '%s'::text, count(*) from %s 
      $fmt$, tname, tname); 
    END LOOP; 
END $$; 

WITH row_counts AS (SELECT * FROM show_row_count()) 
SELECT * FROM row_counts 
UNION ALL 
SELECT 'TOTAL'::text, sum(row_count) FROM row_counts; 

瞭解更多:Executing Dynamic Commands

1

如果你想與個人ROW_COUNTS表做

SELECT nspname AS schemaname,relname,reltuples 
FROM pg_class C 
LEFT JOIN pg_namespace N ON (N.oid = C.relnamespace) 
WHERE 
    nspname NOT IN ('pg_catalog', 'information_schema') AND 
    relkind='r' 
ORDER BY reltuples DESC 

`

所有行的總數中的所有表都

With infotables as 
(
SELECT nspname AS schemaname,relname,reltuples 
FROM pg_class C 
LEFT JOIN pg_namespace N ON (N.oid = C.relnamespace) 
WHERE 
    nspname NOT IN ('pg_catalog', 'information_schema') AND 
    relkind='r' 
ORDER BY reltuples DESC 
) 
select sum(reltuples) from infotables` 

參考:How do you find the row count for all your tables in Postgres

+0

謝謝回答,但我對實際的行數沒有真正的興趣。我想了解如何編寫更通用的查詢版本。我已經找到了你提供的鏈接 – AndrewLngdn

1

你可以使用分析函數來獲得每行的總數。

  SELECT 
       nspname AS schemaname, 
       relname AS TABLE_NAME, 
       reltuples AS ROW_COUNT, 
       SUM (reltuples) OVER() AS total_rows_count 
      FROM 
       pg_class C 
      LEFT JOIN pg_namespace N ON (N.oid = C .relnamespace) 
      WHERE 
       nspname = 'ptab' 
      AND relkind = 'r' 
      ORDER BY 
       reltuples DESC