如何选择所有子行

时间:2018-10-08 09:33:19

标签: mysql function stored-procedures

我有一个带有Id,Name和ParentId的表,像这样

Id      Name      ParentId
----+----------+---------
 1      jijo        0
 2      arjun       1(Id)
 3      dijo        2(Id)

当我编写条件ID = 3 时,我想获取所有子行。 我尝试了很多代码,但是很不幸。...

DELIMITER //
DROP PROCEDURE IF EXISTS `view_master_data_child_rows` //
CREATE  PROCEDURE `view_master_data_child_rows`(IN SearchID INT) 
  DECLARE ParentId INT DEFAULT SearchID;

  IF ParentId != 0 THEN
    SELECT `ParentId ` INTO ParentId FROM master_data WHERE `Id` = ParentId;
    CALL view_master_data_child_rows(ParentId);
  END IF;

END //
DELIMITER ;

谢谢。

1 个答案:

答案 0 :(得分:0)

尝试自助加入

SELECT A.Id, A.Name,B.ID, B.Name
FROM master_data AS A
LEFT JOIN master_data AS B ON A.Id = B.ParentId
WHERE A.Id = 3;