@ Symbol - a solution for Recursive SELECT query in Mysql?

前端 未结 4 386
孤城傲影
孤城傲影 2020-12-03 12:51

there are a lot of questions about Recursive SELECT query in Mysql, but most of answers is that \"There NO solution for Recursive SELECT query in Mysql\".

Actually t

4条回答
  •  一个人的身影
    2020-12-03 13:42

    Stored procedure is the best way to do it. Because Gordon's solution would work only if the data follows the same order.

    If we have a table structure like this

    col1 - col2 - col3
    3 - k - 7
    5 - d - 3
    1 - a - 5
    6 - o - 2
    2 - 0 - 8
    

    It wont work.

    Here is a sample procedure code to achieve the same.

    delimiter //
    CREATE PROCEDURE chainReaction 
    (
        in inputNo int
    ) 
    BEGIN 
        declare final_id int default NULL;
        SELECT col3 into final_id from table1
        where col1 = inputNo;
        if( final_id is not null) then
            insert into results(select col1, col2, col3 from table1 where col1 = inputNo);
            CALL chainReaction(final_id);   
        end if;
    END//
    delimiter ;
    
    call chainReaction(1);
    select * from results;
    drop table if exists results;
    

提交回复
热议问题