如何在mysql数据库中查询用户所有上级

有时候,一句SQL可以实现的MYSQL递归查询,就不想用存储过程了。如何在MySQL数据库中查询用户所有上级,下面是一个可行的方法,前提是数据库设计一定要标准化,id使用数字型int,pid为0则为顶级。如果使用GUID的可以路过!

下面写出MySQL数据库中查询用户所有上级的SQL语句:

select id as id,preid as 父id ,levels as 父到子之间级数, paths as 父到子路径 from (
     select id,preid,
     @le:= if (preid = 0 ,0,  
         if( locate( concat('|',preid,':'),@pathlevel)   > 0  ,      
                  substring_index( substring_index(@pathlevel,concat('|',preid,':'),-1),'|',1) +1
        ,@le+1) ) levels
     , @pathlevel:= concat(@pathlevel,'|',id,':', @le ,'|') pathlevel
      , @pathnodes:= if( preid =0,',0', 
           concat_ws(',',
           if( locate( concat('|',preid,':'),@pathall) > 0  , 
               substring_index( substring_index(@pathall,concat('|',preid,':'),-1),'|',1)
              ,@pathnodes ) ,preid  ) )paths
    ,@pathall:=concat(@pathall,'|',id,':', @pathnodes ,'|') pathall 
        from  userDepartment, 
    (select @le:=0,@pathlevel:='', @pathall:='',@pathnodes:='') vv
    order by  preid,id
    ) src
order by id

您可能还会对下面的文章感兴趣: