![](/img/trans.png)
[英]syntax error at or near “RETURNING” PSQL Select with returning statement
[英]Parametrizing output of a select statement PSQL
我使用的是基於8.3構建的postgresql版本。 我基於特定的IP地址運行大量查詢,並希望創建一個函數,該函數可以將IP地址作為類似於以下參數的參數傳遞:
CREATE OR REPLACE FUNCTION features.src_forensics(text)
RETURNS SETOF rows as
$$
select src, action,
count(distinct date_trunc('day', receive_time) ) n_activeDay,
count(distinct source_IP) n_src,
count(distinct source_IP) / count(distinct date_trunc('day', receive_time)) n_src_per_day,
sum(bytes) as total_bytes,
min(receive_time) minTime,
max(receive_time) maxTime
from table
where src = $1
group by src, action ;
$$ LANGUAGE sql;
問題是上面的查詢沒有以我慣用的表格式返回select語句的輸出。 如果將10.10.0.1用作函數的IP地址輸入,如何獲得上面編寫的腳本,使其表現得像下面的select語句?
select src, action,
count(distinct date_trunc('day', receive_time) ) n_activeDay,
count(distinct source_IP) n_src,
count(distinct source_IP) / count(distinct date_trunc('day', receive_time)) n_src_per_day,
sum(bytes) as total_bytes,
min(receive_time) minTime,
max(receive_time) maxTime
from table
where src = '10.10.0.1'
group by src, action;
我通常在返回任意列集時執行此操作:
RETURNS TABLE(
src text,
action text,
n_activeDay bigint,
n_src bigint,
n_src_per_day bigint,
total_bytes bigint,
minTime timestamptz,
maxTime timestamptz
) AS
如果您希望保留定義不變,則可以更改查詢函數的方式:
select * from features.src_forensics("a") AS f(
src text,
action text,
n_activeDay bigint,
n_src bigint,
n_src_per_day bigint,
total_bytes bigint,
minTime timestamptz,
maxTime timestamptz
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.