2015-10-30 36 views
0

我有很多像这样的结果在最后结合的查询,所以我可以计算两个不同结果集之间的连接数,然后使用联合查询来生成完整的结果表。这里的问题是使用select into为每个结果创建一个新表,而不是将其存储在内存中。在使用PostgreSQL时,如何将每个结果存储在自己的变量中,而不会在数据库中创建大量假表格,之后我将丢弃它们?在没有在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); 

回答

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' 
    ); 
+0

谢谢!我真的想知道如何做到这一点。在某种程度上,这确实解决了我的问题(只要将v1取出),但我仍然想知道如何将结果存储在某种类型的变量中,而无需在数据库中创建新表。 –

+0

取决于您打算如何处理该变量。你在想光标吗? – trincot

+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

相关问题