I have the table as like below.
CREATE TABLE my.categories (id bigint, parent_id bigint, name varchar(128));
INSERT INTO my.categories (id, parent_id, name) VALUES (1, null, 'LEVEL 1');
INSERT INTO my.categories (id, parent_id, name) VALUES (2, 1, 'LEVEL 2.1');
INSERT INTO my.categories (id, parent_id, name) VALUES (3, 1, 'LEVEL 2.2');
INSERT INTO my.categories (id, parent_id, name) VALUES (4, 2, 'LEVEL 3.1.1');
INSERT INTO my.categories (id, parent_id, name) VALUES (5, 2, 'LEVEL 3.1.2');
INSERT INTO my.categories (id, parent_id, name) VALUES (6, 3, 'LEVEL 3.2.1');
+----+-----------+---------------+
| id | parent_id | name |
+----+-----------+---------------+
| 1 | null | 'LEVEL 1' |
| 2 | 1 | 'LEVEL 2.1' |
| 3 | 1 | 'LEVEL 2.2' |
| 4 | 2 | 'LEVEL 3.1.1' |
| 5 | 2 | 'LEVEL 3.1.2' |
| 6 | 3 | 'LEVEL 3.2.1' |
+----+-----------+---------------+
I need to get all id's for parent categories.
WITH RECURSIVE tree(theId) AS (
SELECT id
FROM my.categories
WHERE id = theId -- wrong here, because its not a procedure
UNION ALL
SELECT table1.id
FROM my.categories AS table1
JOIN tree AS parent ON theId = table1.parent_id
)
SELECT DISTINCT theId FROM tree WHERE theId = 6;
Example result with data but actually I need only id's.
+----+-----------+---------------+
| id | parent_id | name |
+----+-----------+---------------+
| 1 | null | 'LEVEL 1' |
| 3 | 1 | 'LEVEL 2.2' |
| 6 | 3 | 'LEVEL 3.2.1' |
+----+-----------+---------------+
Or like this:
+----+-----------+---------------+
| id | parent_id | name |
+----+-----------+---------------+
| 3 | 1 | 'LEVEL 2.2' |
| 6 | 3 | 'LEVEL 3.2.1' |
+----+-----------+---------------+
The trouble is I'm not allowed to use procedures. This query should be used as sub-query for many other queries. And please dont look at name
column it is irrelevant.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…