SELECT id,pid,v FROM test WHERE ID = 'B' UNION ALL select id,pid,v from ( select t1.id,t1.pid,t1.v, if(find_in_set(pid, @pids) > 0, @pids := concat(@pids, ',', id), 0) as ischild from (select id,pid,v from test t order by pid, id ) t1,(select @pids := 'B') t2) t3 where ischild != '0';