1

我有一个(postgres)sql 表,其中包含以下内容(主机):

   ip_address   |  mac_address   | hostname | device | physical_port
----------------+----------------+----------+--------+---------------
111.111.111.111 | aaaa.aaaa.aaaa | hosta    | swh-a  | Gi1/1
111.111.111.112 | bbbb.bbbb.bbbb | hostb    | swh-b  | Gi2/1
111.111.111.113 | cccc.cccc.cccc | hostc    | swh-c  | Gi3/1

devices我有另一个表(Peers),其中包含在able 表中的点对点链接。

 device | physical_port | peer_device | peer_physical_port 
 -------+---------------+-------------+----------------------+
 swh-a  | Gi1/20        | swh-b       | Gi2/1
 swh-b  | Gi2/1         | swh-a       | Gi1/20
 swh-b  | Gi2/1         | swh-c       | Gi3/1
 swh-c  | Gi3/1         | swh-b       | Gi2/1

基本上,我希望从 Hosts 表中排除包含在 Peers 表中的条目,这样我只能得到:

   ip_address   |  mac_address   | hostname | device | physical_port
----------------+----------------+----------+--------+---------------
111.111.111.111 | aaaa.aaaa.aaaa | hosta    | swh-a  | Gi1/1

(鉴于此device=swh-b physical_port=Gi2/1并且device=swh-c physical_port=Gi3/1存在于 Peers 表中)。

4

4 回答 4

3

您可以使用NOT EXISTS几乎就像英文一样的不言自明查询:

SELECT *
FROM Hosts h
WHERE NOT EXISTS (
    SELECT * FROM Peers p
    WHERE p.peer_device = h.device AND p.peer_physical_port = h.physical_port
)
于 2013-11-13T02:18:54.473 回答
1

这对你有用吗?

SELECT * FROM Hosts
WHERE NOT peer_physical_port IN (
    SELECT DISTINCT peer_physical_port FROM Peers
)

您只选择未出现在第二个表中的条目。

于 2013-11-13T02:18:00.907 回答
0

尝试这个..

SELECT  * 
FROM    Host
WHERE   device NOT IN (SELECT device FROM Peers )
AND     physical_port NOT IN (SELECT physical_port FROM Peers)
于 2013-11-13T04:43:29.173 回答
0

你需要这样的东西:

SELECT *
FROM Host h
LEFT JOIN Peers p ON p.device= h.device and p.physical_port = h.physical_port
WHERE p.ID IS NULL
于 2013-11-13T02:16:04.007 回答