-- 构造测试数据2 CREATE TABLE `treetable` ( `id` int NOT NULL , `name` varchar(50) NOT NULL , `parid` int NOT NULL , PRIMARY KEY (`id`) ) ; insert into treetable select 1,'1',0 union all select 2,'1-1',1 union all select 3,'1-1-1',2 union all select 4,'1-1-1-1',3 union all select 5,'1-1-1-1-1',
-- 递归找父亲 select * from (select id,name,if(id = (select parid from treetable where id= @a),@a := id,0) as hassum from treetable,(select @a := 4) as t1 order by parid desc ) as t where t.hassum !=0;