![](/img/trans.png)
[英]creating table as select is dropping the not null constraints in postgresql
[英]Select into without creating a new table in 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);
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函數或DO
語句中使用SELECT ... INTO variable
。
您可以只使用前兩個查詢作為最終查詢中的子查詢:
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
關鍵字,將在特殊模式中創建臨時表。 在會話結束時將自動刪除它。
附帶說明,下面的較短查詢應返回相同的結果:
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'
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.