2013-03-28 138 views
1

我在一个postgresql 8.3数据库。我正试图找出下面查询中的错误。我试图设计一个查询来只选择私人地址的source_ips和destination_ips。SQL查询选择公共IP地址

由于某种原因,在下面的查询中抓取的地址之一是地址208.117.252.39,它不是私人地址。

下面的查询中的逻辑是否有问题会使它选择公有IP地址?

select source_ip, destination_ip 
from ip_table 
where 
    (
    inet '10/8' >> source_ip 
    or inet '192.168/16' >> source_ip 
    or source_ip >= inet '172.16/16' and source_ip < inet '172.32/16' 
    ) 
    and inet '10/8' >> destination_ip 
    or inet '192.168/16' >> destination_ip 
+0

是,如果更改了相同> =以>>和< to >>? –

+0

为了清楚起见,尝试用“inet”172.16/12'>> source_ip“替换”source_ip> = inet'172.16/16'和source_ip hoxworth

回答

1

,需要相应地组最终条件。现在,最后的“或”忽略了所有的条件。

结构查询作为这样的:

select source_ip, destination_ip 
from ip_table 
where 
(
    inet '10/8' >> source_ip 
    or inet '192.168/16' >> source_ip 
    or inet '172.16/12' >> source_ip 
) 
and (
    inet '10/8' >> destination_ip 
    or inet '192.168/16' >> destination_ip 
    or inet '172.16/12' >> destination_ip 
); 

注意目标子句组合在一起。

1

由于and操作优先于or您缺少括号。您的查询等效于:

select source_ip, destination_ip 
from ip_table 
where 
    (
     (
     inet '10/8' >> source_ip 
     or inet '192.168/16' >> source_ip 
     or source_ip >= inet '172.16/16' and source_ip < inet '172.32/16' 
     ) 
     and inet '10/8' >> destination_ip 
    ) 
    or inet '192.168/16' >> destination_ip 

正确的版本:

select source_ip, destination_ip 
from ip_table 
where 
    (
     inet '10/8' >> source_ip 
     or inet '192.168/16' >> source_ip 
     or source_ip >= inet '172.16/16' and source_ip < inet '172.32/16' 
    ) 
    and 
    (
     inet '10/8' >> destination_ip 
     or inet '192.168/16' >> destination_ip 
    )