mysql 查询所有父级名称

SELECT T2.id, T2.name 
FROM ( 
    SELECT 
        @r AS _id, 
        @stop:=@stop+if(@r=2,1,@stop) as stop,
        (SELECT @r := p_id FROM goods_class WHERE id = _id) AS p_id, 
        @l := @l + 1 AS lvl 
    FROM 
        (SELECT @r := 39, @l := 0, @stop:=0) vars, 
        goods_class h 
    WHERE @stop < 1) T1 
JOIN goods_class T2 
ON T1._id = T2.id 
ORDER BY T1.lvl DESC 

 

posted @ 2018-08-09 17:04  itvita  阅读(2550)  评论(0编辑  收藏  举报