select tbl_1.GroupName,tbl_1.ID,count(*) from tbl_1,tbl_2 where tbl_1.ID = tbl_2.ID group by tbl_2.groupid 这个是sql语句,你换成存储过程吧。

解决方案 »

  1.   

    这是我写的:
    create procedure prInfo
      @userId int
    as
    select tbl_1.GroupName,tbl_1.ID count(tbl_2.ID) as numbers
    from tbl_1 inner join tbl_2 
    on tbl_1.ID = tbl_2.GroupId
    where tbl_1.UserId = @userId
    group by tbl_1.GroupName,tbl_1.ID
    但是这样返回的只有
    GroupName    ID     numbers
    a            1      2
    b            2      2
    其他的分组就没有了
      

  2.   

    create procedure prInfo
      @userId int
    as
    select tbl_1.GroupName,tbl_1.ID count(tbl_2.ID) as numbers
    from tbl_1 left join tbl_2 
    on tbl_1.ID = tbl_2.GroupId
    where tbl_1.UserId = @userId
    group by tbl_1.GroupName,tbl_1.ID
      

  3.   

    接上面:
    而该用户其实还创建了其他的分类,总共创建了6个分组,为什么只返回tbl_2中存在的记录呢
    我想要的是:
    GroupName    ID     numbers
    a            1      2
    b            2      2
    c            3      0
    d            4      0
    e            5      0
    f            6      0
    而不是:
    GroupName    ID     numbers
    a            1      2
    b            2      2
      

  4.   

    因为你的表b中没有c,d,e,f对应的记录。所以inner join的结果不包含c,d,e,f.
    改成left join就可以了
      

  5.   

    另一种写法是left outer join