wuxing164
wuxing164
2010-11-05 16:12

如何做sql的优化

已采纳

最近要从数据库查找相关的数据下面是sql语句
[code="java"]
String sql = "select hed.VHWHLO,hed.VHFIDT,hed.VHPROJ,mat.VMMTNO,mat.VMSPMT,mas.MMITDS,mas.MMUNMS,mas.MMITTY,hed.VHORQT,hed.VHRVQT,mat.VMCNQT,hed.VHWHST,tab.CTTX40,hed.VHELNO from S6513EF0.MVXCDTALIV.MWOHED hed join S6513EF0.MVXCDTALIV.MWOMAT mat on hed.VHFACI=mat.VMFACI and hed.VHPRNO = mat.VMPRNO and hed.VHMFNO = mat.VMMFNO join S6513EF0.MVXCDTALIV.MITMAS mas on mat.VMMTNO = mas.MMITNO join S6513EF0.MVXCDTALIV.CSYTAB tab on mas.MMITCL = tab.CTSTKY where hed.VHCONO = 65 and hed.VHFIDT = ? and hed.vhwhst<80 and hed.VHELNO = ? and tab.CTSTCO='ITCL' and mas.MMITTY = '04' or mas.MMITTY = '05'";
[/code]
我用PreparedStatement来查找然后放到一张新表里面,发现每找一些数据后会停下来,然后再查找
查一千多条记录要20分钟左右
上面关联的表每张大约有6W条数据,查找要这么多时间是不是因为数据多而且还关联4张表
请问有优化的方法吗?谢谢!

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • weixin_42530738 HUAKNDT 11年前

    楼主的SQL是不是写错了,
    and mas.MMITTY = '04' or mas.MMITTY = '05'";

    应该是这样吧and (mas.MMITTY = '04' or mas.MMITTY = '05')";
    不加括号肯定是不对的

    另外UNION的效率比OR要好得多,你改成这样应该会好点
    select hed.VHWHLO,hed.VHFIDT,hed.VHPROJ,mat.VMMTNO,mat.VMSPMT,mas.MMITDS,mas.MMUNMS,mas.MMITTY,hed.VHORQT,hed.VHRVQT,mat.VMCNQT,hed.VHWHST,tab.CTTX40,hed.VHELNO from S6513EF0.MVXCDTALIV.MWOHED hed join S6513EF0.MVXCDTALIV.MWOMAT mat on hed.VHFACI=mat.VMFACI and hed.VHPRNO = mat.VMPRNO and hed.VHMFNO = mat.VMMFNO join S6513EF0.MVXCDTALIV.MITMAS mas on mat.VMMTNO = mas.MMITNO join S6513EF0.MVXCDTALIV.CSYTAB tab on mas.MMITCL = tab.CTSTKY where hed.VHCONO = 65 and hed.VHFIDT = ? and hed.vhwhst<80 and hed.VHELNO = ? and tab.CTSTCO='ITCL' and mas.MMITTY = '04'
    UNION
    select hed.VHWHLO,hed.VHFIDT,hed.VHPROJ,mat.VMMTNO,mat.VMSPMT,mas.MMITDS,mas.MMUNMS,mas.MMITTY,hed.VHORQT,hed.VHRVQT,mat.VMCNQT,hed.VHWHST,tab.CTTX40,hed.VHELNO from S6513EF0.MVXCDTALIV.MWOHED hed join S6513EF0.MVXCDTALIV.MWOMAT mat on hed.VHFACI=mat.VMFACI and hed.VHPRNO = mat.VMPRNO and hed.VHMFNO = mat.VMMFNO join S6513EF0.MVXCDTALIV.MITMAS mas on mat.VMMTNO = mas.MMITNO join S6513EF0.MVXCDTALIV.CSYTAB tab on mas.MMITCL = tab.CTSTKY where hed.VHCONO = 65 and hed.VHFIDT = ? and hed.vhwhst<80 and hed.VHELNO = ? and tab.CTSTCO='ITCL' and mas.MMITTY = '05'

    点赞 评论 复制链接分享

相关推荐