【sql查询】 子查父

SELECT T2.id, T2.category_name   #分列查看

#转换成字符串查看
SELECT GROUP_CONCAT(CONCAT_WS(",",T2.id)  ORDER BY T1.lvl DESC) as treeid
FROM (  
    SELECT  
        @r AS _id,  
        (SELECT @r := parent_id FROM expert_enumeration WHERE id = _id) AS parent_id,  
        @l := @l + 1 AS lvl  
    FROM  
        (SELECT @r := '1252893434476294167', @l := 0) vars,  
        expert_enumeration h  
    WHERE @r <> 0) T1  
JOIN expert_enumeration T2  
ON T1._id = T2.id  
ORDER BY T1.lvl DESC

代码@r := '1252893434476294167’标示查询id为1252893434476294167的所有父类效果如图
在这里插入图片描述
在这里插入图片描述

你可能感兴趣的:(数据库)