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
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;