无需在PostgreSQL中创建新表即可选择

时间:2015-10-30 17:37:35

标签: sql postgresql

我有许多类似的查询,其结果在最后组合,因此我可以计算两个不同结果集之间的连接数,然后使用联合查询生成完整的结果表。这里的问题是使用select into为每个结果创建一个新表而不是将其存储在内存中。使用PostgreSQL时,如何将每个结果存储在自己的变量中,而不会在数据库中创建一大堆伪造的表,之后我会丢弃它们?

select distinct cust_num into t1 
from all_visits_x_cust 
where date > '06/02/2015'
and date <= '07/02/2015' 
and cust_num > 9999;

select distinct cust_num into t1_2 
from cc_calls_x_cust 
where date = '06/02/2015' 
and cust_num > 9999);

select count(*) as post_call_visitors 
into v1 
from t1_2 join t1 
on t1.cust_num = t1_2.cust_num);

2 个答案:

答案 0 :(得分:2)

Postgres中没有全局变量。您可以使用with query以一个方式运行这些查询:

with t1 as (
    select distinct cust_num
    from all_visits_x_cust 
    where date > '06/02/2015'
    and date <= '07/02/2015' 
    and cust_num > 9999
    ),
t1_2 as (
    select distinct cust_num into t1_2 
    from cc_calls_x_cust 
    where date = '06/02/2015' 
    and cust_num > 9999
    )
select count(*) as post_call_visitors 
from t1_2 
join t1 
on t1.cust_num = t1_2.cust_num;

您可以在PL/pgSQL functionDO statement中使用SELECT ... INTO variable

答案 1 :(得分:1)

您可以在最终查询中使用前两个查询作为子查询:

select count(*) as post_call_visitors 
into temp v1
from (
        select distinct cust_num
        from all_visits_x_cust 
        where date > '06/02/2015'
        and date <= '07/02/2015' 
        and cust_num > 9999
    ) as t1
join (
        select distinct cust_num 
        from cc_calls_x_cust 
        where date = '06/02/2015' 
        and cust_num > 9999
     ) as t1_2
on t1.cust_num = t1_2.cust_num; 

确保删除这些子查询的into子句。他们最后在as部分得到了他们的名字。

通过在第二行使用temp关键字,将在特殊模式中创建temporary表。它将在会话结束时自动删除。

作为旁注,下面较短的查询应返回相同的结果:

select count(distinct cust_num) as post_call_visitors 
from cc_calls_x_cust 
where date = '06/02/2015' 
and cust_num > 9999
and cust_num in (
        select cust_num 
        from all_visits_x_cust 
        where date > '06/02/2015'
        and date <= '07/02/2015' 
    );