2010-02-09 76 views
0

我有以下问题:我的表是大到足够多的(数以百万计的数据行),这是我处理的临时数据。我需要根据某些标准选择一列的最大值和最小值,处理这些信息并根据相同的标准删除数据。其实,最简单的实现看起来像:删除和返回数据的PostgreSQL

select max(col), min(col) from _TABLE_ where _CONDITION_; 
... 
delete from _TABLE_ where _CONDITION_; 

表是很大的,当我处理它,quering循环这种方式,它需要一定的时间。我想我可以用“回归”中删除优化它,像

delete from _TABLE_ where _CONDITION_ returning max(col), min(col); 

这是绝对是我所需要的,但是......它不会在所有:)说话,我不能使用聚合函数工作在返回的条款等

有改善两个查询(选择数据的最大/最小和删除同一数据)作出一个查询,而不是什么好办法?任何诡计?

感谢您事先的任何信息, Maxym

+0

是_CONDITIONS_相互排斥的,相对较低数? – cope360 2010-02-09 19:53:19

+0

对不起,你的意思是?实际上,“col”.. hm,实际上我有两列,分别表示点(纬度和经度)的坐标,所以我选择根据矩形删除表中的所有点,但是我必须知道min/max经度和经度的删除点(真实的,因为我可以采取长方形:) – Maxym 2010-02-14 01:44:20

回答

1

使用这样的功能:

create temporary table test (value int); 
insert into test select generate_series(1,100); 

create or replace function delete_even_from_test_and_return_min_deleted() 
    returns int as 
$$ 
declare 
    _value record; 
    min int; 
begin 
    min=X'7FFFFFFF'; -- INT_MAX 
    for _value in 
    delete from test where value%2=0 returning value 
    loop 
    if min>_value.value then 
     min=_value.value; 
    end if; 
    end loop; 
    return min; 
end; 
$$ language plpgsql; 

select count(*) from test; 
100 

select delete_even_from_test_and_return_min_deleted(); 
2 

select count(*) from test; 
50 
+0

谢谢你,我会尝试一下Mon – Maxym 2010-02-14 01:46:12

7

你可以这样做:

with foo as(delete from table where _CONDITION_ returning col) 
select max(col), min(col) from foo 
+1

为什么只能从9.1?这个想法是使用CTE功能,对吧?它也是在8.4中启用的。 – Maxym 2012-05-15 12:07:32

+0

是的,你是对的。我认为你不能在9.1之前使用(...)DELETE/INSERT:http://www.postgresql.org/docs/9.1/static/queries-with.html。我只是混淆了一切,谢谢! – 2012-05-18 15:48:08