我想撰寫一個 Postgres 函式,它從其他表中獲取各種統計資訊并將結果組合到一行中。
例如
select count(*) as acount from tableA
select count(*) as bcount from tableB
select count(*) as ccount from tableC
回傳
acount, bcount, ccount as a single record
顯然,上面列出的“計數”函式比這要復雜得多,甚至每個表的計數可能不同。
那么理想情況下是否可以將它們存盤為變數,然后從變數中構建記錄?
uj5u.com熱心網友回復:
不需要變數,您可以將所有內容組合成一個帶有子查詢的 select 陳述句:
select
(select count(*) from tableA) as acount,
(select count(*) from tableB) as bcount,
(select count(*) from tableC) as ccount;
uj5u.com熱心網友回復:
您可以使用交叉連接
select * from
(select count(*) as acount from tableA) as a
,(select count(*) as bcount from tableB) as b
,(select count(*) as ccount from tableC) as c
uj5u.com熱心網友回復:
您還可以創建一個由 3 個 bigint 型別組成的新型別。
CREATE TYPE mutli_count AS (
_countt1 bigINT,
_countt2 bigint,
_countt3 bigINT
);
select(
(select count(*) from country),
(select count(*) from states),
(select count(*) from cities))::mutli_count;
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/443416.html
標籤:sql PostgreSQL 功能
