美文网首页
mysql递归级联查询

mysql递归级联查询

作者: 装完逼立马跑 | 来源:发表于2018-03-22 14:44 被阅读0次

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



    需要的结果:公司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递归级联查询

          本文链接:https://www.haomeiwen.com/subject/ncyaqftx.html