Skip to content

Instantly share code, notes, and snippets.

@adrianuf22
Created April 11, 2018 19:21
Show Gist options
  • Save adrianuf22/83c3c0ed68840f398dc4e8afd8ed4031 to your computer and use it in GitHub Desktop.
Save adrianuf22/83c3c0ed68840f398dc4e8afd8ed4031 to your computer and use it in GitHub Desktop.
Arvore com pais e filhos de um prefix
create table tree (
id INT,
path VARCHAR(255),
name VARCHAR(100)
);
insert into tree VALUES (1, '/', 'Prédio Orozimbo');
insert into tree VALUES (2, '/1', 'Ala a');
insert into tree VALUES (3, '/1', 'Ala b');
insert into tree VALUES (4, '/1/2', 'RH');
insert into tree VALUES (5, '/1/2', 'ADM');
insert into tree VALUES (6, '/1/3', 'Tecnico');
insert into tree VALUES (7, '/1/3', 'Visitante');
insert into tree VALUES (8, '/1/3/7', 'sala b');
insert into tree VALUES (9, '/1/3/7/8', 'sala d');
insert into tree VALUES (10, '/1/2/5', 'sala a');
insert into tree VALUES (11, '/1/2/5', 'sala c');
insert into tree VALUES (12, '/1/3/6', 'pc a', 'lo','192.169.0.10/32');
update tree set prefix = '192.168.0.1/30' where id = 3
update tree set prefix = '192.168.0.5/30' where id = 7
select parent.id, parent.name, parent.path from tree leaf
join tree as parent ON (leaf.path LIKE CONCAT('%', parent.id, '%'))
where leaf.prefix = '192.168.0.5/30'
UNION ALL
select children.id, children.name, children.path from tree leaf
join tree as children
where leaf.prefix = '192.168.0.5/30'
AND ((leaf.name = children.name AND leaf.path = children.path)
OR children.path LIKE CONCAT(leaf.path,'/',leaf.id,'%'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment