有如下数据表与数据
通过递归查询到如下数据
select * from comments where find_in_set(pid,getChildLst(1));
我希望通过add_date和level来排序,得到如下结果
id   pid    level
6     1       1
3     1       1
7     3       2
2     1       1
4     2       2
5     4       3新手不懂,请大师们指教如何写select语句,或者有什么思路可实现。非常感谢。

解决方案 »

  1.   

    select * from comments where find_in_set(pid,getChildLst(1)) order by find_in_set(pid,getChildLst(1))
      

  2.   

    为什么ID=2的记录在7的后面?是这样的:先按level=1记录的时间倒序排序,然后排序level=1时id值的所有子记录(递归查找),递归完之后查找下一条level=1的记录和子记录,依次循环。
      

  3.   

    id=2-7的记录都是id=1的子记录,或者通过select语句能否得到如下的结果:字段名   ids
    第一行    6
    第二行   3,7
    第三行  2,4,5
      

  4.   


    感谢ACMAIN_CHM版主,但经查询,查询得到的结果如下:
      

  5.   

    需要改 getChildLst( 中的算法,改广度优先为深度优先。
      

  6.   


    getChildLst函数如下:DROP FUNCTION `getChildLst`//
    CREATE DEFINER=`root`@`localhost` FUNCTION `getChildLst`(rootId INT) RETURNS varchar(1000) CHARSET latin1
    Begin
    Declare sTemp varchar(1000);
    Declare sTempChd varchar(1000);
    Set sTemp = '$';
    Set sTempChd = cast(rootId as CHAR);
    While sTempChd is not null Do
    Set sTemp = concat(sTemp,',',sTempChd);
    Select group_concat(id) into sTempChd from comments where find_in_set(pid,sTempChd)>0;
    End While;
    Return sTemp;
    End这是网上的一段函数,菜鸟未能理解,请ACMAIN_CHM版主帮忙看一下如何改,非常感谢。
      

  7.   

    还以为你已经看过下面这个贴子了。http://blog.csdn.net/acmain_chm/article/details/4142971MySQL中进行树状所有子节点的查询
    在Oracle 中我们知道有一个 Hierarchical Queries 通过CONNECT BY 我们可以方便的查了所有当前节点下的所有子节点。但很遗憾,在MySQL的目前版本中还没有对应的功能。 在MySQL中如果是有限的层次,比如我们事先如果可以确定这个树的最大深度是4, 那么所有节点为根的树的深度均不会超过4,则我们可以直接通过left join 来实现。 但很多时候我们...
      

  8.   

    结贴了,用ACMAIN_CHM版主提供材料的第三个方法解决问题,谢谢大家。