Mysql 查询所有的上级,下级

-- 查询所有下级
SELECT t3.id, t3.parentId pid, t3.tname name FROM (
    SELECT t1.*, IF(find_in_set( parentId, @pids ) > 0, @pids := concat( @pids, ',', id ), 0 ) isChild
    FROM ( SELECT id, parentId, tname FROM TableName t ORDER BY parentId, id ) t1, ( SELECT @pids := 2 ) t2 ) t3
WHERE
    isChild != 0  

 说明tableName为表名,@pids:=2 代表是要查询的父id

-- 查询所有上级		
SELECT t2.id, t2.parentId, t2.tname
FROM ( 
    SELECT  @id as _id, 
        (SELECT @id := parentId FROM TableName WHERE id = _id) p
    FROM 
        (SELECT @id := 4476) v, 
        TableName 
    WHERE @id <> 0) t1 
JOIN TableName t2 ON t1._id = t2.id 

说明TableName 为表名,@id:=4476 代表要查询的子id

你可能感兴趣的:(mysql,数据库,sql)