mysql checks all sons according to the father, and checks the top parent according to the son

Oracle can use connect by prior to perform parent-child query, while mysql does not have this function and needs to write the process by itself.
Note: pi_orgId is the condition value; pi_isQueryChild: Whether to check the parent or child, true is to check all the sons, false is to check the top-level father; pi_columName is the list, pi_parentColumName is the parent column name, and pi_tableName is the table name.
The code example is as follows:

DELIMITER $$



USE `ivbs`$$



DROP PROCEDURE IF EXISTS `sp_recursive_query`$$



CREATE DEFINER=`root`@`%` PROCEDURE `sp_recursive_query`(IN pi_orgId VARCHAR(300),IN pi_isQueryChild BOOLEAN ,IN pi_columNam VARCHAR(50),IN pi_parentColumName VARCHAR(50) ,IN pi_tableName VARCHAR(50), OUT pi_out_str VARCHAR(1000))
BEGIN
    DECLARE sTemp VARCHAR (4000) ;
    SET sTemp = '$' ;
    SET @sTempChd = CAST(pi_orgId AS CHAR ) ;
    WHILE
    @sTempChd IS NOT NULL DO SET sTemp = CONCAT(sTemp, ',', @sTempChd ) ;
    IF pi_isQueryChild THEN
        -- 找儿子
          SET @V_SQL := CONCAT('SELECT  GROUP_CONCAT(',pi_columNam,') INTO @sTempChd  FROM test_myt WHERE FIND_IN_SET(' , pi_parentColumName,',\'',@sTempChd,'\') > 0') ;
         PREPARE stmt FROM @V_SQL;
          EXECUTE stmt  ;
         DEALLOCATE PREPARE  stmt;  
      ELSE
        -- 找父亲
         SET @V_SQL := CONCAT('SELECT  GROUP_CONCAT(',pi_parentColumName,') INTO @sTempChd  FROM test_myt WHERE FIND_IN_SET(' , pi_columNam,',\'',@sTempChd,'\') > 0');
         PREPARE stmt FROM @V_SQL;
         EXECUTE stmt;
         DEALLOCATE PREPARE  stmt;  
     END IF;
  END WHILE ;
  SET pi_out_str=sTemp;
END$$



DELIMITER ;

Call:
CALL sp_recursive_query('1',TRUE,'org_id','org_parent_id','table_name',@result);
SELECT @result;

Result: $ ,1,6,7,100,11,12 (through 1, find all the sons, this is the format of the result, find the father, pass false for the second parameter, the others are the same)

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326862956&siteId=291194637