class表 id   classname  bigid 
1    大类一      0 
2    小类一      1 
3    大类二      0 
4    大类三      0 
5    小类二      1 
6    小类三      3 



//这是一个类别的表,其中通过bigid来实现大小类的区分及关联,bigid对应前面的id,如果bigid是0,表示它是大类,如果bigid不是0,则表示它是该id的小类,通过下面代码调出相关的类别 public string classall() 
    {         //连接数据库 
        SqlCommand cmd = new SqlCommand("SELECT top 6 * FROM class where bigid=0", objConnection); 
        //省略 
        while (dr.Read()) 
        { 
          if(dr[""]){
            strBody += "" + dr["classname"] + "(有小类)"; 
          }
          else{
            strBody += "" + dr["classname"] + "";
         }
        } 
        //关闭 
    } //我想实现的是优先显示有小类的大类名字,并在后面加上 “有小类”三个字,请问上面的if语句和select语句该怎么写呢?谢谢

解决方案 »

  1.   

       //连接数据库  
            SqlCommand cmd = new SqlCommand("SELECT top 6 a.*,(select count(b.*) from class b where b.bigid=a.id) as counts FROM class a where a.bigid=0",  objConnection);  
            //省略  
            while (dr.Read())  
            {  
              if(dr["couts"].ToString()!="0")   //连接数据库  
                       strBody += "" + dr["classname"] + "(有小类)";  
              } 
              else{ 
                strBody += "" + dr["classname"] + ""; 
             } 
            }  
            //关闭  
      

  2.   

    select c.classname, b.subClassCount from class c,
    (select bigid, count(*) as subClassCount
    from class where bigid<>0 group by bigid) b
    where c.id = b.bigid
    order by b.subClassCount desc
      

  3.   

    建议表设计改为:
    --------------------------
    class表  id   classname  parentId  
    1    大类一        0  
    2    小类一        1  
    3    大类二        0  
    4    大类三        0  
    5    小类二        3  
    6    小类三        4  
    --------------------------