我在Heroku(PostgreSQL)中有许多数据字段,可以通过多个关系调用数据范围。对于过去一周的数据,我有类似以下的查询:
SELECT x, y, ts FROM (
SELECT x1 as x, y1 as y, t1.mytimestamp as ts
FROM t1, t2
WHERE ... t1.mytimestamp::date > (CURRENT_TIMESTAMP - interval '8' day)::date
UNION
SELECT x2 as x, y2 as y, t3.mytimestamp as ts
FROM t3, t4
WHERE ... t3.mytimestamp::date > (CURRENT_TIMESTAMP - interval '8' day)::date
UNION
...(etc)...
) ORDER BY ts DESC
有没有办法将像这样的字符串保存为变量,所以要更改所有查询的日期范围(即“'8'日” - >“'366'日”)我只需要改变字符串一次而不是每次发生?我发现一些线程说在一个函数中声明变量,但由于某种原因,似乎没有任何工作。
在heroku的文档中它只是说'使用标准SQL' - 函数/变量不是标准的sql特性吗?任何建议都赞赏,谢谢!
答案 0 :(得分:3)
我会使用CTE做类似的事情:
WITH vars AS (
SELECT
interval '8' day AS "range"
)
SELECT x, y, ts FROM (
SELECT x1 as x, y1 as y, t1.mytimestamp as ts
FROM t1, t2, vars
WHERE ... t1.mytimestamp::date > (CURRENT_TIMESTAMP - vars.range)::date
UNION
SELECT x2 as x, y2 as y, t3.mytimestamp as ts
FROM t3, t4
WHERE ... t3.mytimestamp::date > (CURRENT_TIMESTAMP - vars.range)::date
UNION
...(etc)...
) ORDER BY ts DESC
答案 1 :(得分:1)
将其包装在SQL函数中:
CREATE OR REPLACE FUNCTION my_whatever_func(integer)
returns table(x integer, y integer, ts timestamp)
as $$
SELECT x, y, ts FROM (
SELECT x1 as x, y1 as y, t1.mytimestamp as ts
FROM t1, t2
WHERE ... t1.mytimestamp::date > (CURRENT_TIMESTAMP - interval $1 day)::date
UNION
SELECT x2 as x, y2 as y, t3.mytimestamp as ts
FROM t3, t4
WHERE ... t3.mytimestamp::date > (CURRENT_TIMESTAMP - interval $1 day)::date
) ORDER BY ts DESC
$$ language sql;
并使用:
调用SELECT * FROM my_whatever_func(8);
这种查询模式表明您可能希望使用表继承。