• Mysql 根据id查所有父级或子级


    查询子级 使用存储过程

    delimiter //
    
    drop PROCEDURE IF EXISTS  showChildLst//
    
    CREATE PROCEDURE showChildLst (IN rootid INT)
    BEGIN
     DECLARE Level int ;
     drop TABLE IF EXISTS tmpLst;
     CREATE TABLE tmpLst (
      id int,
      nLevel int,
      sCort varchar(8000)
     );
     
     Set Level=0 ;
     INSERT into tmpLst SELECT id,Level,ID FROM crm_presona_dk WHERE presona_pid=rootid;
     WHILE ROW_COUNT()>0 DO
      SET Level=Level+1 ;
      INSERT into tmpLst 
       SELECT A.id,Level,concat(B.sCort,'-',A.id) FROM crm_presona_dk A,tmpLst B 
        WHERE  A.presona_pid=B.id AND B.nLevel=Level-1  ;
     END WHILE;
      
    END;
    //
    
    delimiter ;
    
    call showChildLst(2);
    select * from tmpLst;

    查询父级直接用sql

    数据表的结构:
    id  name    parent_id 
    --------------------------- 
    1   Home        0 
    2   About       1 
    3   Contact     1 
    4   Legal       2 
    5   Privacy     4 
    6   Products    1 
    7   Support     1 
    
    SELECT T2.id, T2.name 
    FROM ( 
        SELECT 
            @r AS _id, 
            (SELECT @r := parent_id FROM table1 WHERE id = _id) AS parent_id, 
            @l := @l + 1 AS lvl 
        FROM 
            (SELECT @r := 5, @l := 0) vars,  --查询id为5的所有上级
            table1 h 
        WHERE @r <> 0) T1 
    JOIN table1 T2 
    ON T1._id = T2.id 
    ORDER BY T1.lvl DESC
  • 相关阅读:
    vue 中使用阿里iconfont彩色图标
    团队作业九
    团队作业八
    团队作业七
    第二篇
    第三篇
    第一篇
    beta冲刺计划安排
    团队作业六
    团队作业五
  • 原文地址:https://www.cnblogs.com/adjk/p/14986302.html
Copyright © 2020-2023  润新知