我使用的是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;
答案 0 :(得分:1)
我通常在返回任意一组列时执行此操作:
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
);