mysql递归级联查询

需求:三级联级,需要根据当前订单中的设备信息,查到它的所有上级信息



需要的结果:公司A-品牌B-机型A-设备B


之前强行写的sql虽然能满足要求,但是效率堪忧
下方为sql,'333'为ID

SELECT equipment_Id,equipment_name,type,equipment_parentcode
    FROM ( 
        SELECT 
                @r AS id, 
                (SELECT @r := equipment_parentcode FROM equipment WHERE equipment_Id = id) AS pid, 
                 @l := @l + 1 AS lvl 
        FROM 
                (SELECT @r := 333, @l := 0) vars, 
                equipment h 
        WHERE @r <> 0
        ) T1 
    JOIN equipment T2 
    ON T1.id = T2.equipment_Id
ORDER BY equipment_Id;

你可能感兴趣的:(mysql递归级联查询)