仅当子网是给定IP列表的一部分时才获得一行

仅当子网是给定IP列表的一部分时才获得一行

本文介绍了后期| SQL |仅当子网是给定IP列表的一部分时才获得一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有文本列的表,其中包含带有子网的ip

I have a table with text column that holds ip with subnet

| ip
-------------
| 1.1.1.1/30

当您将1.1.1.1/30转换为IP列表时,您会得到:

when you convert 1.1.1.1/30 to list of ip you get:

1.1.1.0
1.1.1.1
1.1.1.2
1.1.1.3

我想在此表上运行sql并以某种方式给出ips列表作为"where"部分的一部分.或其他任何内容,并且仅当我给出的ip列表中包含该行范围内的ip时,才获得此行.

I want to run a sql on this table and give a list of ips somehow as part of "where" or anything else, and get this row only if the list of the ips that I give contain the ips of the range in the row.

含义

where ('1.1.1.0','1.1.1.1)

->我不会得到这一行

--> I will not get the row

但是:

where ('1.1.1.0','1.1.1.1,1.1.1.2,1.1.1.3)

->我会得到的行

--> I will get the row

但是:

where ('1.1.1.0','1.1.1.1,1.1.1.2,1.1.1.3,1.1.1.4,1.1.1.5)

->我会得到的行

--> I will get the row

反正有这样做吗?

推荐答案

您必须将inet扩展到其所有host值,然后使用遏制来做到这一点:

You have to expand out the inet into all its host values and then use containment to accomplish this:

with blowout as (
  select t.ip, array_agg(host(network(t.ip::inet) + gs.n)) as all_ips
    from t
   cross join lateral
         generate_series(0, broadcast(t.ip::inet) - network(t.ip::inet)) as gs(n)
   group by t.ip;
)
select *
  from blowout
 where all_ips <@ array['1.1.1.0', '1.1.1.1', '1.1.1.2',
                        '1.1.1.3', '1.1.1.4', '1.1.1.5']::text[]
;

由于在比较中没有使用任何特殊的inet函数,因此最好使用text进行比较.

Since you are not using any special inet functions in the comparison, it is best to do the comparisons using text.

这篇关于后期| SQL |仅当子网是给定IP列表的一部分时才获得一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 14:44