如何使用 postgres 查询最小值或最大值 inet/cidr
how to query for min or max inet/cidr with 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.
因此,我创建了一个名为 temp 的 table 并填充它:
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)
因此,我可以使用 host() 转换为文本,但会产生不正确的答案:
select min(host(d)) from temp;
那是因为它在做一个文本'min'函数,就是这样排序:
# 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 类型的 min() 和 max() 函数?有一些方法可以欺骗它(转换为 int 并进行比较,或者进行有限制的排序)。我对适当的 min() 和 max() 更感兴趣。谢谢!
-g
我又看了一遍,pg还是不支持min(inet)。我想你可以做的是制作另一列来映射 inet,例如 replace(r,'.','') 和 min() 它。
您可以使用现有函数 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)
考虑查询:
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.
因此,我创建了一个名为 temp 的 table 并填充它:
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)
因此,我可以使用 host() 转换为文本,但会产生不正确的答案:
select min(host(d)) from temp;
那是因为它在做一个文本'min'函数,就是这样排序:
# 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 类型的 min() 和 max() 函数?有一些方法可以欺骗它(转换为 int 并进行比较,或者进行有限制的排序)。我对适当的 min() 和 max() 更感兴趣。谢谢!
-g
我又看了一遍,pg还是不支持min(inet)。我想你可以做的是制作另一列来映射 inet,例如 replace(r,'.','') 和 min() 它。
您可以使用现有函数 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)