三个表:
1.学校表(school):id,schoolname,createdate
2.学生表(student):id,username,schoolid,createdate
3.评论表(comment):id,comment,schoolid,createdate现在想用一条SQL语句获得如下数据(不用存储过程):
select school.id, school.schoolname, count(student.id) as countstudent, count(comment.id) as countcomment from ... where (or ...on) school.id=student.schoolid and school.id=comment.schoolid请高手赐教,不胜感谢!

解决方案 »

  1.   

    select a.id, a.schoolname, 
    sum(case when b.id is not null then 1 else 0 end ) as '学校数量',
    sum(case when b.id is not null then 1 else 0 end ) as '评论数量'
    from 学校表 a left join 学生表 b on a.id=b.schoolid
    left join 评论表 c on a.id=c.schoolid
    group by a.id, a.schoolname
      

  2.   

    SQL codeselect a.id, a.schoolname, 
    sum(case when b.id is not null then 1 else 0 end ) as '学校数量',
    sum(case when b.id is not null then 1 else 0 end ) as '评论数量'
    ---------是否为sum(case when C.id is not null then 1 else 0 end ) as '评论数量'
    from 学校表 a left join 学生表 b on a.id=b.schoolid
    left join 评论表 c on a.id=c.schoolid
    group by a.id, a.schoolname1楼厉害
      

  3.   

    select a.id, a.schoolname, 
    sum(case when b.id is not null then 1 else 0 end ) as '学生数量',
    sum(case when c.id is not null then 1 else 0 end ) as '评论数量'
    from 学校表 a left join 学生表 b on a.id=b.schoolid
    left join 评论表 c on a.id=c.schoolid
    group by a.id, a.schoolname
    1楼厉害 
      

  4.   

    select id, schoolname, 
        ( select count(*) from student where schoolid = a.id ) as countstudent,
        ( select count(*) from comment where schoolid = a.id ) as countcomment
    from school a