weixin_45326504
weixin_45326504
2021-07-22 23:41
采纳率: 100%
浏览 24

MYSQL 5.8 如何递归查询路径 举例如下

img
一个表ABC ,两列UID 和PID , 现在需要得到UID 与PID 的路径关系如下:
img
这个是用SQLSERVER的 with as 递归查询语句得出的结果。 请问 用MYSQL 语句如何得出这个结果。请给出MYSQL 的查询语句。

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • technologist_32
    CSDN专家-Time 2021-07-23 22:35
    已采纳
    CREATE FUNCTION func(M INT,N INT) RETURNS varchar(50)
    BEGIN
      DECLARE str varchar(50) DEFAULT '';
      DECLARE p int DEFAULT 0;
        DECLARE u int DEFAULT 0;
      DECLARE count int DEFAULT 0;
        set p = N;
      set u = M;
      set count = 0;
        if p = 0 Then
         set str = concat(u,'');
      end if;
      while p != 0 do
    
        select uid into u from a where pid = p and uid = u;
      select pid into p from a where pid = p and uid = u;
          if p = 0 THEN
          set p = 0;
        else 
          if count = 0 THEN
                        set str = concat(p,"->",u,str);
          else
              set str = concat(p,"->",str);
          end if;
            end if;
        set u = p;
        set count= count+1;
            select pid into p from a where uid = u;
       end while;
     
      RETURN (
          # Write your MySQL query statement below.
            str
          );
    END;
    
    

    img

    点赞 1 评论
  • technologist_32
    CSDN专家-Time 2021-07-23 09:09

    用循环或者用游标。

    点赞 评论
  • weixin_45326504
    weixin_45326504 2021-07-24 08:13

    谢谢 ,mysql里 用这个查询语句出结果只要13秒 ,在SQLSERVER 里用with as 递归查询需要30秒+; 只是PATH太长超过最大值的话 ,在MYSQL里就会出问题。

    点赞 评论

相关推荐