How to find all child rows in MySQL?

后端 未结 3 2003
再見小時候
再見小時候 2021-01-27 09:29

I have a hierarchy system setup that stores the level and parent ID of the item in a database. What I am trying to figure out is how would I go about finding all the child rows

3条回答
  •  滥情空心
    2021-01-27 10:29

    Refer, Recursive MySQL Query with relational innoDB

    I had posted a answer yesterday for the same

    Update:

    Below is a function based on the above link, but has been tailored for your DELETE requirements

    CREATE PROCEDURE `delete_relations`(`_id` INT)
    BEGIN
    DECLARE  delete_row_ids varchar(200);
    DECLARE id, id2 varchar(200);
    DECLARE rows_affected int;
    
    SET delete_row_ids  = _id;
    SET id              = _id;
    SET id2             = id;
    
    WHILE id2 IS NOT NULL DO 
        SET id = NULL;
        SELECT GROUP_CONCAT( hierarchical_data.id ), CONCAT( GROUP_CONCAT( hierarchical_data.ID ),',',delete_row_ids) INTO id, delete_row_ids FROM hierarchical_data WHERE FIND_IN_SET( parentid , id2 ) GROUP BY parentid ;
        SET id2 = id;
    END WHILE;  
    
    DELETE FROM hierarchical_data where FIND_IN_SET(hierarchical_data.id, delete_row_ids);
    SELECT row_count() INTO rows_affected;
    
    if rows_affected > 0 THEN
    SELECT delete_row_ids as row_ids_deleted;
    ELSE
    SELECT 'NO_ROWS_DELETED';
    END IF;
    
    END//
    

    SQLFiddle

    Use

    CALL delete_relations(1)
    

    To delete all entries and its relations for id = 1 honda

    Hope its helpful

提交回复
热议问题