Note that there are some explanatory texts on larger screens.

plurals
  1. POPostgresql join only most specific cidr match
    primarykey
    data
    text
    <p>I have a table "test_networks" that is a list of networks with a description about what each network is and where it is located.</p> <pre><code>CREATE TABLE test_networks ( id serial PRIMARY KEY, address cidr, description text ); </code></pre> <p>The field "address" will be any of the following:</p> <ul> <li>10.0.0.0/8</li> <li>10.1.0.0/16</li> <li>10.1.1.0/24</li> <li>10.2.0.0/16</li> <li>10.3.0.0/16</li> <li>10.3.1.0/24</li> <li>10.3.2.0/24</li> <li>10.3.3.0/24</li> <li>10.15.1.0/24</li> <li>10.15.2.0/24</li> <li>10.15.3.0/24</li> </ul> <p>I also have a table "test_systems" which contains a list of systems and their properties (I have a few more properties, but those are irrelevant):</p> <pre><code>CREATE TABLE test_systems ( id serial PRIMARY KEY, address inet, owner text ); </code></pre> <p>Lets assume I have systems with the following addresses:</p> <ul> <li>10.1.1.1</li> <li>10.2.0.1</li> </ul> <p>I want to create a report of all systems and their closest <em>networks</em> description (or empty description if no network is found). As you can see, 10.1.1.1 matches multiple networks, so I only want to list the most specific one (i.e. the one with the highest masklen()) for each system. Example output would be:</p> <pre><code> 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 </code></pre> <p>I tried using this query:</p> <pre><code>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 &lt;&lt; n.address; </code></pre> <p>However, this will give me a list of all system + network pairs, e.g.:</p> <pre><code> 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 </code></pre> <p>Does anyone know how I can query for only the most specific network for each system?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload