mybaitis书写sql需要特别注意where条件中的语句,否则将会导致索引失效,使得查询总是超时。如下语句会出现导致索引失效的情况:
with test1 as (select count(C_FUNDACCO) val,‘a‘ v from TINF_REQUEST a where a.C_FUNDCODE = #{cFundcode} and a.D_DATADATE = #{dDatadate}), test2 as (select count(C_FUNDACCO) val,‘a‘ v from TINF_CONFIRM b where b.C_FUNDCODE = #{cFundcode} and b.D_DATADATE = #{dDatadate}), test3 as (select count(C_FUNDACCO) val,‘a‘ v from TINF_DIVIDENDDETAIL c where c.C_FUNDCODE = #{cFundcode} and c.D_DATADATE = #{dDatadate}), test4 as (select count(C_FUNDACCO) val,‘a‘ v from TINF_SHAREDETAIL f where f.C_FUNDCODE = #{cFundcode} and f.D_DATADATE = #{dDatadate}) select test1.val requestCount,test2.val confirmCount,test3.val dividendCount,test4.val shareDeatilCount from test1,test2,test3,test4 where test1.v=test2.v and test2.v=test3.v and test3.v=test4.v
原因:直接使用#{dDatadate}导致索引的失效。
sql语句中出现几种情况会导致索引失效:
1.TO_CHAR(a.D_DATADATE, ‘yyyy-mm-dd‘) <= TO_CHAR(#{dDatadateStart}, ‘yyyy-mm-dd‘),导致索引失效。
2.trunc(created)>=TO_DATE(‘2013-12-14‘, ‘YYYY-MM-DD‘),导致索引失效。
3.c.D_DATADATE = #{dDatadate},导致索引失效。
将上述语句加上TO_DATE函数,改为如下语句,不会导致索引失效:
with test1 as (select count(C_FUNDACCO) val,‘a‘ v from TINF_REQUEST a where a.C_FUNDCODE = #{cFundcode} and a.D_DATADATE = TO_DATE(#{dDatadate},‘yyyy-MM-dd‘)), test2 as (select count(C_FUNDACCO) val,‘a‘ v from TINF_CONFIRM b where b.C_FUNDCODE = #{cFundcode} and b.D_DATADATE = TO_DATE(#{dDatadate},‘yyyy-MM-dd‘)), test3 as (select count(C_FUNDACCO) val,‘a‘ v from TINF_DIVIDENDDETAIL c where c.C_FUNDCODE = #{cFundcode} and c.D_DATADATE = TO_DATE(#{dDatadate},‘yyyy-MM-dd‘)), test4 as (select count(C_FUNDACCO) val,‘a‘ v from TINF_SHAREDETAIL f where f.C_FUNDCODE = #{cFundcode} and f.D_DATADATE = TO_DATE(#{dDatadate},‘yyyy-MM-dd‘)) select test1.val requestCount,test2.val confirmCount,test3.val dividendCount,test4.val shareDeatilCount from test1,test2,test3,test4 where test1.v=test2.v and test2.v=test3.v and test3.v=test4.v
百万、千万级别的数据,加上索引并且使索引生效的sql语句,查询性能会很快。如果sql使得索引失效,将会总是超时,无法加载出来数据。
因此书写sql一定要注意自己写的sql是否使得索引生效,查看执行计划
FULL全表扫描即未使用索引(或索引失效);INDEX使用索引查询,会使得查询效率非常高。
总结:百万、千万级别的数据,在查询sql上使用索引查询,会很大的提高性能。
原来表中不加索引的查询需要5分钟甚至更长时间导致查询超时;加上索引后并且sql使用索引生效,会使得查询几秒就能查询出来数据。
所以利用好索引,即使面对百万、千万、上亿条数据也不用担心查询超时。
原文地址:https://www.cnblogs.com/super-chao/p/9888537.html
时间: 2024-11-06 04:42:20