1

I have a tree-like structure for categories on my database:

create table cat(
     id int auto_increment primary key,
     url varchar(50),
     parent int references cat(id)
)

How can i build the URL of a category, by concatenating its url with the parent url? (until parent is not null)

I'm using MariaDB 10.2

1
  • Did you try recursive CTE? Commented Feb 6, 2021 at 1:39

1 Answer 1

4

This recursive CTE will form a URL out of each level in the table, joining them with a / (although that is easily changed). The desired final node is specified in the CTE (in this example, it is 7):

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

Demo on dbfiddle

You can get all of the available paths by omitting the WHERE id = condition from the CTE. For my sample data, that gives:

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

Demo on dbfiddle

Sign up to request clarification or add additional context in comments.

3 Comments

for real? that easy? it's almost 2 hours that i try trillion queries
I've written a few of these in my time... :)
Note I updated the query/demo to add a prefix to the URL as well. You can easily change all those string constants as necessary.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.