SQLserver2000中有两张表
主题表Title 字段:id, title,t_content  (id主键自增,title标题 字符型,t_content主题内容 字符型)  
                    
回复表Reply 字段:id, r_id,r_content  (id主键自增,r_id回复的主题 整型,r_content回复内容 字符型)两张表通过r_id外键关联。 也就是通常论坛里的主题对应的回复。现在要查询主题的所有字段以及每个主题对应的回复个数,请问这sql语句该怎么写,有不同的写法更好

解决方案 »

  1.   

    select a.*,b.qty
    from title a
    left join (select r_id,count(*) as 'qty' from reply group by r_id)t on a.id=b.r_id
      

  2.   

    select a.id,a.title,a.content,b.r_content
    from title a
      join reply b
        on a.id=b.r_id
    select a.title,a.content,count(b.r_id) cnt
    from title a
      join reply b
         on a.id=b.r_id
    group by a.title,a.content
      

  3.   

    select a.*,(select count(*) from reply where r_id=a.id) as '回复数'
    from title a 
      

  4.   

    select distinct a.*,[count]=count(1) from Title a left join Reply b on a.id=b.r_id  
      

  5.   


    select  a.*,b.[count] from Title a left join (select r_id,[count]=count(1) from  Reply group by r_id) b on a.id=b.r_id  
      

  6.   

    SQLserver2000中有两张表 
    主题表Title 字段:id, title,t_content  (id主键自增,title标题 字符型,t_content主题内容 字符型)   
                         
    回复表Reply 字段:id, r_id,r_content  (id主键自增,r_id回复的主题 整型,r_content回复内容 字符型) 两张表通过r_id外键关联。 也就是通常论坛里的主题对应的回复。 现在要查询主题的所有字段以及每个主题对应的回复个数,请问这sql语句该怎么写,有不同的写法更好select m.* , isnull(n.cnt,0) 回复 from title m,
    left join
    (
      select r_id , count(*) cnt from reply group by r_id
    ) n
    on m.id = n.r_id
      

  7.   

    select *,num=(select count(1) from reply where a.id=r_id) from title a
      

  8.   

    select *,num=isnull((select count(1) from reply where a.id=r_id),0) from title a
      

  9.   

    select a.*,b.qty 
    from title a 
    left join (select r_id,count(*) as 'qty' from reply group by r_id)b on a.id=b.r_id谢谢大家的回答, ~与君共勉~可否简单解释一下上面的句子
      

  10.   

    select r_id,count(*) as 'qty' from reply group by r_id
    这语是返回每个主题ID的记录数(也就是回复数),count(*)按r_id分组后,每个r_id的总记录数再和title表按id关联,即返回每个贴子的回复数