Lad mig give dig en idé. Opret en funktion, der henter parent_id fra et givet ID et antal gange, lad os kalde det generation. Cat10 generation 1 ville være forælder, som er CAT5 generation 2 ville være CAT3 og så videre.
DROP FUNCTION IF EXISTS getNameIdGeneration;
DELIMITER $$
CREATE FUNCTION getNameIdGeneration(idPar int, generationPar int)
RETURNS VARCHAR(1000) READS SQL DATA
BEGIN
DECLARE auxLoopVar INT default 0;
DECLARE parentIdVar INT default idPar;
DECLARE nameVar VARCHAR(1000) default NULL;
count_loop: LOOP
SELECT parent_id INTO parentIdVar FROM Category_parent WHERE Category_id = parentIdVar;
SET auxLoopVar = auxLoopVar + 1;
IF auxLoopVar >= generationPar THEN
LEAVE count_loop;
END IF;
END LOOP;
SELECT name INTO nameVar FROM Category WHERE id = parentIdVar;
RETURN nameVar;
END;
$$
DELIMITER ;
forudsat at Category_Id for CAT10 =10, hvis du tester den angivne funktion
select getNameIdGeneration(10, 2);
CAT3
Nu mangler du bare en tabel, som indeholder id'et for den CAT, du vil kende dens afstamning
MariaDB [mydatabase]> select * from test;
+-------------+------------+
| category_id | generation |
+-------------+------------+
| 10 | 1 |
| 10 | 2 |
| 10 | 3 |
+-------------+------------+
MariaDB [mydatabase]> select generation, getNameIdGeneration(category_id, generation) as Name from test;
+------------+------+
| generation | Name |
+------------+------+
| 1 | CAT5 |
| 2 | CAT3 |
| 3 | CAT1 |
+------------+------+
3 rows in set (0.00 sec)