By using db<>fiddle, you agree to license everything you submit by Creative Commons CC0.
create table cat(
id int auto_increment primary key,
url varchar(50),
parent int references cat(id)
)
insert into cat (url, parent) values
('home', null),
('user', 1),
('apps', 1),
('nick', 2),
('excel', 3),
('word', 3),
('docs', 4)
Records: 7 Duplicates: 0 Warnings: 0
select *
from cat
id | url | parent |
---|---|---|
1 | home | null |
2 | user | 1 |
3 | apps | 1 |
4 | nick | 2 |
5 | excel | 3 |
6 | word | 3 |
7 | docs | 4 |
WITH RECURSIVE urls AS (
SELECT url, parent
FROM cat
WHERE id = 7
UNION ALL
SELECT CONCAT_WS('/', cat.url, urls.url), cat.parent
FROM urls
JOIN cat ON cat.id = urls.parent
)
SELECT CONCAT('http://', url) AS url
FROM urls
WHERE parent IS NULL
url |
---|
http://home/user/nick/docs |
WITH RECURSIVE urls AS (
SELECT id, url, parent
FROM cat
UNION ALL
SELECT urls.id, CONCAT_WS('/', cat.url, urls.url), cat.parent
FROM urls
JOIN cat ON cat.id = urls.parent
)
SELECT CONCAT('http://', url) AS url
FROM urls
WHERE parent IS NULL
url |
---|
http://home |
http://home/apps |
http://home/user |
http://home/apps/excel |
http://home/apps/word |
http://home/user/nick |
http://home/user/nick/docs |