2016-02-02 68 views
2

最大INET/CIDR考慮查詢:如何查詢分鐘或者Postgres的

select min(d) from temp; 
select max(d) from temp; 

任一個,我得到一個錯誤,如:

# select max(d) from temp; 
ERROR: function max(inet) does not exist 
LINE 1: select max(d) from temp; 
      ^
HINT: No function matches the given name and argument types. You might need to add explicit type casts. 

所以,我創建一個表所謂的氣溫和填充它:

create table temp (d inet); 
insert into temp (d) values ('1.1.10.2'); 
insert into temp (d) values ('1.1.10.10'); 
insert into temp (d) values ('1.1.10.20'); 
insert into temp (d) values ('1.1.10.100'); 

# select * from temp order by d; 

    d  
------------ 
1.1.10.2 
1.1.10.10 
1.1.10.20 
1.1.10.100 
(4 rows) 

所以,我可以使用主機()轉換爲文本,而是產生不正確的答案:

select min(host(d)) from temp; 

那是因爲它是做一個文本「分鐘」功能,這是這個順序:

# select host(d) as r from temp order by r; 
    r  
------------ 
1.1.10.10 
1.1.10.100 
1.1.10.2 
1.1.10.20 
(4 rows) 

是否有在Postgres的IP類型一分鐘()和MAX()函數?有辦法來欺騙它(轉換爲int並進行比較,或者通過限制進行排序)。我對適當的min()和max()更感興趣。謝謝你這麼!

-g

+0

我讀到這http://www.postgresql.org/message-id/[email protected]om和我認爲已經有一個補丁修復了這個問題。但我嘗試了PG9.3它失敗了,我的朋友試圖在9.4它失敗too.i認爲你可以做的是映射到int和使用min()在那 –

回答

1

可以使用現有的功能network_smaller(inet, inet)network_larger(inet, inet)定義自己的集合體:

create aggregate min (inet) (
    sfunc = network_smaller, 
    stype = inet); 

create aggregate max (inet) (
    sfunc = network_larger, 
    stype = inet); 

select min(d) min, max(d) max 
from temp; 

    min | max  
----------+------------ 
1.1.10.2 | 1.1.10.100 
(1 row) 
+0

謝謝!我知道這種工作。我剛剛讀過9.3之後存在的min()和max(),但我無法找到它們。我希望得到一個答案,告訴我如何使用min()和max()。 – Greg

+0

我發現了一個更好的解決方案,請參閱編輯答案。 – klin

+0

這真的不是你要找的東西嗎?該解決方案儘可能接近Postgres的核心。 – klin

0

我再次檢查,pg仍然不支持min(inet)。我想你可以做的是製作另一列來映射inet,像replace(r,'。',''')和min()它。