Đây Chủ đề dẫn tôi. Cảm ơn @RolandoMySQLDBA
DELIMITER $$
DROP FUNCTION IF EXISTS `GetAncestry` $$
CREATE FUNCTION `GetAncestry` (GivenID INT) RETURNS VARCHAR(1024)
DETERMINISTIC
BEGIN
DECLARE rv VARCHAR(1024);
DECLARE cm CHAR(1);
DECLARE ch INT;
SET rv = '';
SET cm = '';
SET ch = GivenID;
WHILE ch > 0 DO
SELECT IFNULL(`prent`,-1) INTO ch FROM
(SELECT `prent` FROM Table1 WHERE id = ch) A;
IF ch > 0 THEN
SET rv = CONCAT(rv,cm,ch);
SET cm = ',';
END IF;
END WHILE;
RETURN rv;
END $$
DELIMITER ;
fiddle đang hoạt động đây.
SELECT id,GetAncestry(id) as parents from Table1 where id = 7;
ID PARENTS
7 6,3,2,1