The code below is from: https://www.freecodecamp.org/news/mysql-common-table-expressions/
Data:
CREATE TABLE
categories (
id int,
cat_name varchar(100),
parent_category_id int DEFAULT NULL
);
INSERT INTO
categories
VALUES
(1, 'Mens', NULL),
(2, 'Tops', 1),
(3, 'Jerseys', 2),
(4, 'England', 3);
Code:
WITH RECURSIVE
category_tree AS (
SELECT
id,
cat_name,
parent_category_id,
cat_name AS full_name
FROM categories
WHERE parent_category_id IS NULL
UNION ALL
SELECT
c.id,
c.cat_name,
c.parent_category_id,
CONCAT (ct.full_name, ' > ', c.cat_name)
FROM categories c
JOIN category_tree ct
ON c.parent_category_id = ct.id
)
SELECT
id, full_name
FROM
category_tree;
categories:
| id | cat_name | parent_category_id |
| ---| ---------| -------------------|
| 1 | Mens | NULL |
| 2 | Tops | 1 |
| 3 | Jerseys | 2 |
| 4 | England | 3 |
category_tree:
| id | full_name |
| ---| ------------------------------- |
| 1 | Mens |
| 2 | Mens > Tops |
| 3 | Mens > Tops > Jerseys |
| 4 | Mens > Tops > Jerseys > England |
- I have trouble understanding this line:
ON c.parent_category_id = ct.id - From my understanding, ct.id will always return id: 1 and cat_name: 'Mens'.
- Shouldn't the category_tree CTE stop at "Mens > Tops"?
I would be grateful for any detailed explanations. Thank you very much.