2

I have a number of dataclips in Heroku (PostgreSQL) that call for a data range, over multiple relations. For data of the past week, I have something like the following query:

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

Is there a way to save a string like this as a variable, so to change the date range (ie "'8' day" -> "'366' day") over all queries I'd only need to change the string once rather than for each incidence? I've found some threads that say to declare the variable within a function, but for some reason nothing seems to work.

In heroku's docs it just says 'use standard SQL' - are functions / variables not a standard sql feature? Any advice appreciated, thx!

4

2 回答 2

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
于 2013-11-02T03:14:33.067 回答
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);

这种查询模式表明您可能希望使用表继承。

于 2013-06-04T00:10:50.710 回答