使用临时表缓存查询结果

时间:2018-08-27 03:40:36

标签: amazon-redshift ddl

我想缓存大选择查询的结果以备将来使用。这个想法是使用临时表(我相信它对于会话或至少对于事务而言都是持久的):

CREATE TEMP TABLE cache AS (SELECT * FROM t)

但是当已经创建缓存时,我会遇到以下错误:

Invalid operation: relation "cache" already exists;

CREATE TEMP TABLE ... AS 语句没有 IF NOT EXISTS 条件。所以问题是,这种情况下有什么解决方法吗?

1 个答案:

答案 0 :(得分:1)

如果您只想存储会话中最后一个“大查询”的结果,则

Drop table if exists cache; 
Create temp table cache as 
select * from t where "your's conditions";

之前删除缓存表不会阻止您的创建表语句。

如果您要存储所有“大查询”的结果,那么在缓存的命名中将需要一些额外的信息。

您可以检查语句中是否已存在临时表

IF (select count(*) 
      from information_schema.tables 
     where table_name'cache' 
       and table_schema like 'pg_temp%')=0 THEN

  create temp table cache as 
  select * from t where "your's conditions";
ELSE
  select * from cache where "your's conditions";
END;