sql - How to do the Recursive SELECT query in MySQL? -
i got following table:
col1 | col2 | col3 -----+------+------- 1 | | 5 5 | d | 3 3 | k | 7 6 | o | 2 2 | 0 | 8
if user searches "1", program @ col1
has "1" value in col3
"5", program continue search "5" in col1
, "3" in col3
, , on. print out:
1 | | 5 5 | d | 3 3 | k | 7
if user search "6", print out:
6 | o | 2 2 | 0 | 8
how build select
query that?
edit
solution mentioned @leftclickben effective. can use stored procedure same.
create procedure get_tree(in id int) begin declare child_id int; declare prev_id int; set prev_id = id; set child_id=0; select col3 child_id table1 col1=id ; create temporary table if not exists temp_table (select * table1 1=0); truncate table temp_table; while child_id <> 0 insert temp_table select * table1 col1=prev_id; set prev_id = child_id; set child_id=0; select col3 child_id table1 col1=prev_id; end while; select * temp_table; end //
we using temp table store results of output , temp tables session based wont there not issue regarding output data being incorrect.
sql fiddle demo
try query:
select col1, col2, @pv := col3 'col3' table1 join (select @pv := 1) tmp col1 = @pv
sql fiddle demo
:
| col1 | col2 | col3 | +------+------+------+ | 1 | | 5 | | 5 | d | 3 | | 3 | k | 7 |
note
parent_id
value should lesschild_id
solution work.
Comments
Post a Comment