我有一个(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
我有另一个表(Peers),其中包含功能表中devices
之间的点对点链接。
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
基本上,我希望Peers表中包含的Hosts表中的排除条目,这样我才能得到:
ip_address | mac_address | hostname | device | physical_port
----------------+----------------+----------+--------+---------------
111.111.111.111 | aaaa.aaaa.aaaa | hosta | swh-a | Gi1/1
(鉴于Peers表中存在device=swh-b physical_port=Gi2/1
和device=swh-c physical_port=Gi3/1
)。
答案 0 :(得分: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
)
答案 1 :(得分:1)
这对你有用吗?
SELECT * FROM Hosts
WHERE NOT peer_physical_port IN (
SELECT DISTINCT peer_physical_port FROM Peers
)
您只选择未出现在第二个表格中的条目。
答案 2 :(得分: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
答案 3 :(得分:0)
试试这个..
SELECT *
FROM Host
WHERE device NOT IN (SELECT device FROM Peers )
AND physical_port NOT IN (SELECT physical_port FROM Peers)