select * from ( 
 select r1.id, r1.rubbertype_id, r1.peiliaoCode, r1.lianjiaoren, r1.inDate, r1.inQuantity, r1.inNote, r1.outDate, r1.outQuantity, r1.product_id, r1.group_id, r1.liuhuaWorker_id, r1.isShenHe, r1.baozhiqi, r1.tuikuQuantity,rt.name as rtname ,w.name as lhname ,w.code,g.name as groupname,r2.kc,pro.code as pcode,r1.baozhiqi as bzq1,r1.writer,r1.lianjiaoren as ljr1 from rubberstore r1 left join ( 
 select rs.rubbertype_id, rs.peiliaoCode,(ifnull(sum(rs.inquantity),0) +ifnull(sum(rs.tuikuquantity),0) - ifnull(sum(rs.outquantity),0) ) as kc  
 from rubberstore rs left join rubbertype rt on rt.id=rs.rubbertype_id  group by rs.rubbertype_id, rs.peiliaoCode ) r2  
 on r2.rubbertype_id=r1.rubbertype_id and r2.peiliaoCode=r1.peiliaoCode 
 left join rubbertype rt on rt.id=r1.rubbertype_id 
 left join worker w on w.id = r1.liuhuaWorker_id 
 left join t_group g on g.id=r1.group_id 
 left join product pro on pro.id=r1.product_id) tp   order by rubbertype_id
MySQL的数据库,5000多条数据,查询要1.5秒,请大家帮忙优化一下,谢谢

解决方案 »

  1.   

    把外层的select * 去掉, order by 放到里面试试
      

  2.   

    这 SQL 给谁看啊?乱七八糟的!格式没有,表结构没有,查询逻辑没有,简直就不知道在写啥!
      

  3.   

    可以把左连接的作为where中查
      

  4.   

    太多的left join,除了建索引,其他没办法。自己去查下mysql操作手册,里面有章专门讲了优化sql
      

  5.   

    把r2建一张视图,然后left join r1,不知道速度会不会快点。
    order by 很浪费时间。