r/mysql • • Dec 05 '24

question Nested Range Tree Query

Hi, all - been turning this one over in my brain, and can't seem to suss out the logic for the life of me, here. This may ultimately be a PHP/MySQL/CSS-combo question, but I'll try to keep things as MySQL-centric as possible, here

I have a single table, with multiple ranges of IP addresses, in decimal and octal form, arranged as such:

description | starting_ip_dec | starting_ip | ip_range
------------------------------------------------------
Group 1     | 167772160       | 10.0.0.0    | 512
Group 1.1   | 167772160       | 10.0.0.0    | 128
Group 1.2   | 167772288       | 10.0.0.128  | 128
Group 2     | 167772672       | 10.0.2.0    | 256
Group 2.1   | 167772772       | 10.0.2.100  | 8
Group 3     | 167772928       | 10.0.3.0    | 256

I'm trying to figure out how to construct a query and output a nested tree that has groups 1.1 and 1.2 displayed as children inside of group 1, and group 2.1 displayed as a child inside of group 2, etc.

This has probably been done before in some fashion, but I haven't been able to come across any examples after multiple searches. Thank you for any help than can be provided!

1 Upvotes

6 comments sorted by

View all comments

Show parent comment

1

u/ssnoyes Dec 09 '24

For example:

WITH RECURSIVE 
parent_cte AS (
    SELECT tbl.description, parent.description as parent_description 
    FROM tbl 
    LEFT JOIN tbl AS parent 
        ON parent.starting_ip_dec <= tbl.starting_ip_dec 
        AND parent.starting_ip_dec + parent.ip_range > tbl.starting_ip_dec + tbl.ip_range 
    LEFT JOIN tbl excluder 
        ON excluder.starting_ip_dec <= tbl.starting_ip_dec 
        AND excluder.starting_ip_dec + excluder.ip_range > tbl.starting_ip_dec + tbl.ip_range 
        AND excluder.ip_range < parent.ip_range 
    WHERE excluder.ip_range IS NULL
), 
cte as (
    SELECT description, parent_description, CAST(description AS CHAR(255)) AS h, 0 AS level 
    FROM parent_cte 
    WHERE parent_description IS NULL 
    UNION ALL 
    SELECT parent_cte.description, parent_cte.parent_description, CONCAT(h, ',', parent_cte.description), level + 1 
    FROM cte JOIN parent_cte ON cte.description = parent_cte.parent_description
) 
SELECT concat(repeat(' ', level), description) FROM cte order by h;

1

u/AdventurousElk770 Dec 21 '24

Just following up- I think I implemented it wrong in the first attempt, as it seems to be working now.

Thanks, again, for your help!