mysql问题描述:有三个表 a,b,c;  a表有字段a_id(主键),name; b表b_id(主键),a_id,b_name; c表c_id(主键),busi_id,a_id,b_id(可以为null),c表可能没有记录或者说不完整要求统计:c表busi_id数量,需要查出的列有 name,b_name,busi_id数量(count(busi_id))备注:c表有记录,有多少统计多少,没有的话,记录也要展示出来,busi_id数量0表示
a表a_id不一定在b表a_id中出现。求sql解决方案,可以几条sql实现(非mysql实现也行,注明即可)

解决方案 »

  1.   


    --试试这个
    select t1.name,t2.b_name,busi_id数量=(select count(busi_id) from c where c_id=t3.c_id) from c t3
    left join a t1 on t1.a_id=t3.a_id
    left join b t2 on t2.b_id=t3.b_id
      

  2.   

    1.这个数据库的表设计有问题,a是b 的父,b是c的父,可是a又是c的父,这种结构必须保证数据不能有交叉,如果有交叉,父子关系便出错了.
    2.楼主的需求描述不太清楚,你倒底是要输出全部信息,还是输出统计信息?做了个例子,可以实现,程序应该可以在MYSQL 里运行,但不敢保证适合你的需求.create table a(a_id int,name varchar(10))
    create table b(b_id int,a_id int,b_name varchar(10))
    create table c(busi_id int,a_id int,b_id int)
    insert into a select 1,'aa'
    insert into a select 2,'bb'
    insert into b select 1,1,'afds'
    insert into b select 2,1,'awef'
    insert into b select 3,2,'vais'
    insert into c select 51,1,2
    insert into c select 13,1,1
    --insert into c select 38,2,2  --这样的记录是有问题的
    go
    select a.name,b.b_name,c.busi_id,
    (select count(*) from c t where t.a_id=a.a_id and t.b_id=b.b_id)ct
    from a left join b on a.a_id=b.a_id
    left join c on c.a_id=a.a_id and c.b_id=b.b_id
    /*
    name       b_name     busi_id     ct
    ---------- ---------- ----------- -----------
    aa         afds       13          1
    aa         awef       51          1
    bb         vais       NULL        0(3 行受影响)*/
    go
    drop table a,b,c
      

  3.   

    select
       a.name,b.b_name,c.busi_id
    from
       a left join b
    on
       a.a_id=b.a_id
    left join
       (select  busi_id,a_id,b_id,count(1) as num from c group by a_id,b_id,busi_id)c
    on
       c.a_id=a.a_id and c.b_id=b.b_id
      

  4.   

    --修改
    select
       a.name,b.b_name,c.num
    from
       a left join b
    on
       a.a_id=b.a_id
    left join
       (select  busi_id,a_id,b_id,count(1) as num from c group by a_id,b_id,busi_id)c
    on
       c.a_id=a.a_id and c.b_id=b.b_id
      

  5.   

    谢谢各位的热情帮助,各位提供的想法对我有所启示,由于表设计方面是第三方提供的,理解“qianjin036a
    (晴天)”提的问题,谢谢各位,尤其是 qianjin036a
    (晴天)