我有两表 company 与order,order中有company的外键,company_id,现在做两表联查,要求查出某时间段内的全部company的订单,如果订单数量为0则显示零。语句如下:select c.id,c.name,c.code,sum(c.id) 
from company c left join order d on c.id=d.company_id
where   d.gmt_created>"2012-06-01" 
and d.gmt_created<"2012-07-01" 
and (d.status_bcsticket in(2,4) or d.status_issueticket =5)(这个是查询条件)
group by c.id想要的结果是这样的:id   name   code     sum   
001  a公司  00a      20
002  b公司  00b      0
003  c公司  00c      0
004  e公司  00e      10但现在只能显示出这样:
id   name   code     sum   
001  a公司  00a      20
大家有办法吗,谢谢指教,急用。

解决方案 »

  1.   

    你company里的公司名全不全呢?全的话应该没问题呀,用 company 左连接当然是以公司为标准的嘛。
      

  2.   

    select c.id,c.name,c.code,sum(c.id)  
    from company c left join order d on c.id=d.company_id
    and d.gmt_created>"2012-06-01"  
    and d.gmt_created<"2012-07-01"  
    and (d.status_bcsticket in(2,4) or d.status_issueticket =5)(这个是查询条件)
    group by c.id
      

  3.   

    select c.id,c.name,c.code,sum(c.id)  
     from company c left join order d on c.id=d.company_id
     where d.gmt_created>"2012-06-01"  
     and d.gmt_created<"2012-07-01"  
     and (d.status_bcsticket in(2,4) or d.status_issueticket =5)(这个是查询条件)
     group by c.id,c.name,c.code
      

  4.   

    select c.id,c.name,c.code,sum(c.id)  
    from company c left join (select * from `order` where gmt_created>"2012-06-01"  and gmt_created<"2012-07-01"  and (status_bcsticket in(2,4) or status_issueticket =5) ) d on c.id=d.company_id
    group by c.id
      

  5.   

    贴建表及插入记录的SQL,及要求结果出来看看
      

  6.   

    恩,前几天的帖子给忘掉了,原因就是因为多了个该死的where,导致返回结果一定是两个表的结果集……我晕菜