日期:2014-05-17  浏览次数:20751 次

My SQL 中怎么递归查询所有的父节点

怎么根据某个menuId一直往上查,查到所有的父节点,我用的是my sql 数据库。其SQL语句怎么写?

------解决方案--------------------
有sql 和存储过程  sql ,存储过程 
------解决方案--------------------
只用一句SQL是办不到的,有个办法是在程序中写个递归的方法,方法参数是你想要查询的节点和一个List,然后方法里根据此节点去查父节点,当查出来的父节点不是“0”就把父节点放入参数里的List,并且递归调用自己,直到父节点为“0”,最后,参数的List里的值就是你要的结果了
------解决方案--------------------

    
//获取表中所有id
protected List<Long> getIdList(String sql, Object ... params) {
return xxx;
}

//获取该menu下的所有子节点
private List<Long> getMenuChildrenIds(long menuId) {
        String sql = "select menu_id from test_tb where p_id = ? ";
        return getIdList(sql, menuId);
}
    
public void getAllChildren(long menuId, List<Long> menuIdList) {
        List<Long> childrenIds = getMenuChildrenIds(menuId);
        for (long menu_Id : childrenIds) {
            menuIdList.add(menu_Id);
    //计数
            int count = geliDao.count("select count(1) from test_tb where p_id = ? ", menu_Id, status);
            if (count > 0) {
                getAllChildren(menu_Id, menuIdList);
            }
        }
}

//
public List<Menu> getMenuChildren(long menuId) {
        return orm.list(Menu.class, getMenuChildrenIds(menuId    ).toArray());
    }

//执行,全找出来menuIds,放到list里面
List<Long> menuIds = new ArrayList<Long>();
menuIds.add(menu.getMenuId());
getAllChildren(menu.getMenuId(), menuIds);


大概就是这么个意思了,我也胡乱贴上去的,希望对你有帮助
------解决方案--------------------
mysql不支持这个,楼主可以考虑一下自己写个放在类中
循环遍历取父ID,拼成string 或者 json
再或者只有更改表结构,
如A  id:01
  B  id:0101
  C  id:010101