我有一个表“test_networks”,它是一个网络列表,其中包含每个网络的内容和位置。
CREATE TABLE test_networks
(
id serial PRIMARY KEY,
address cidr,
description text
);
字段“地址”将是以下任何一种:
我还有一个表“test_systems”,其中包含一系列系统及其属性(我还有一些属性,但这些属性无关紧要):
CREATE TABLE test_systems
(
id serial PRIMARY KEY,
address inet,
owner text
);
假设我的系统具有以下地址:
我想创建所有系统及其最近的网络描述的报告(如果没有找到网络,则为空描述)。如您所见,10.1.1.1匹配多个网络,因此我只想列出每个系统中最具体的一个(即具有最高masklen()的网络)。示例输出将是:
hostaddr | netaddr | description
----------+-------------+----------------
10.1.1.1 | 10.1.1.0/24 | third network
10.2.0.1 | 10.2.0.0/16 | 4th network
我尝试使用此查询:
SELECT s.address AS hostaddr, n.address AS netaddr, n.description AS description
FROM test_systems s
LEFT JOIN test_networks n
ON s.address << n.address;
但是,这将为我提供所有系统+网络对的列表,例如:
hostaddr | netaddr | description
----------+-------------+----------------
10.1.1.1 | 10.0.0.0/8 | first network
10.1.1.1 | 10.1.0.0/16 | second network
10.1.1.1 | 10.1.1.0/24 | third network
10.2.0.1 | 10.0.0.0/8 | first network
10.2.0.1 | 10.2.0.0/16 | 4th network
有谁知道如何只查询每个系统中最具体的网络?
答案 0 :(得分:5)
您正在寻找“组中的前n个”查询,在这种情况下n = 1。您可以使用row_number()
窗口函数执行此操作:
SELECT x.hostaddr, x.netaddr, x.description FROM (
SELECT
s.address AS hostaddr,
n.address AS netaddr,
n.description AS description,
row_number() OVER (
PARTITION BY s.address
ORDER BY masklen(n.address) DESC
) AS row
FROM test_systems s
LEFT JOIN test_networks n
ON s.address << n.address
) x
WHERE x.row = 1;
答案 1 :(得分:2)
SELECT distinct on (s.address)
s.address AS hostaddr,
n.address AS netaddr,
n.description AS description
FROM
test_systems s
LEFT JOIN
test_networks n ON s.address << n.address
order by s.address, masklen(n.address) desc