PostgreSQL Count occurrences of contained IP in subnets list

PostgreSQL Count occurrences of contained IP in subnets list



I have a PostgreSQL 9.5 DB set-up with two tables.


t_hosts


t_subnets



t_hosts contains a list of ip addresses and t_subnets a list of subnets.


t_hosts


t_subnets



I want to know for each subnet in t_subnets the number of contained (>>) ip address from t_hosts.


t_subnets


>>


t_hosts



I've put together an extremely inefficient request with a nested count. I'm looking for a more elegant and optimised way of addressing this problem (my current solution is too slow).



Current solution:


CREATE MATERIALIZED VIEW example.mv_count_hosts_in_subnets AS
WITH hosts AS (
SELECT host FROM example.t_hosts
)
SELECT subnet, (SELECT COUNT(host) FROM hosts WHERE subnet >> host) FROM
example.t_subnets WITH NO DATA



Any idea?





Please provide sample data, desired results, and some explanation of what "ineffiicient" means.
– Gordon Linoff
Aug 23 at 10:46





The CTE (with ...) is completely useless and likely to make things slower. Just use t_hosts directly inside your scalar sub-query
– a_horse_with_no_name
Aug 23 at 11:49


with ...


t_hosts





What data types are subnet and host? Posting the complete CREATE statements of the tables wouldn't harm either.
– sticky bit
Aug 23 at 12:05


subnet


host


CREATE









By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Edmonton

Crossroads (UK TV series)