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, &#39;yyyy-mm-dd&#39;) <&#61; TO_CHAR(#{dDatadateStart}, &#39;yyyy-mm-dd&#39;)&#xff0c;导致索引失效。
2.trunc(created)>&#61;TO_DATE(&#39;2013-12-14&#39;, &#39;YYYY-MM-DD&#39;)&#xff0c;导致索引失效。
3.c.D_DATADATE &#61; #{dDatadate}&#xff0c;导致索引失效。
将上述语句加上TO_DATE函数&#xff0c;改为如下语句&#xff0c;不会导致索引失效&#xff1a;
with test1 as (select count(C_FUNDACCO) val,&#39;a&#39; v from TINF_REQUEST a
where a.C_FUNDCODE &#61; #{cFundcode} and a.D_DATADATE &#61; TO_DATE(#{dDatadate},&#39;yyyy-MM-dd&#39;)),
test2 as (select count(C_FUNDACCO) val,&#39;a&#39; v from TINF_CONFIRM b
where b.C_FUNDCODE &#61; #{cFundcode} and b.D_DATADATE &#61; TO_DATE(#{dDatadate},&#39;yyyy-MM-dd&#39;)),
test3 as (select count(C_FUNDACCO) val,&#39;a&#39; v from TINF_DIVIDENDDETAIL c
where c.C_FUNDCODE &#61; #{cFundcode} and c.D_DATADATE &#61; TO_DATE(#{dDatadate},&#39;yyyy-MM-dd&#39;)),
test4 as (select count(C_FUNDACCO) val,&#39;a&#39; v from TINF_SHAREDETAIL f
where f.C_FUNDCODE &#61; #{cFundcode} and f.D_DATADATE &#61; TO_DATE(#{dDatadate},&#39;yyyy-MM-dd&#39;))
select test1.val requestCount,test2.val confirmCount,test3.val dividendCount,test4.val shareDeatilCount from test1,test2,test3,test4 where test1.v&#61;test2.v and test2.v&#61;test3.v and test3.v&#61;test4.v
百万、千万级别的数据&#xff0c;加上索引并且使索引生效的sql语句&#xff0c;查询性能会很快。如果sql使得索引失效&#xff0c;将会总是超时&#xff0c;无法加载出来数据。
因此书写sql一定要注意自己写的sql是否使得索引生效&#xff0c;查看执行计划
FULL全表扫描即未使用索引(或索引失效)&#xff1b;INDEX使用索引查询&#xff0c;会使得查询效率非常高。
总结&#xff1a;百万、千万级别的数据&#xff0c;在查询sql上使用索引查询&#xff0c;会很大的提高性能。
原来表中不加索引的查询需要5分钟甚至更长时间导致查询超时&#xff1b;加上索引后并且sql使用索引生效&#xff0c;会使得查询几秒就能查询出来数据。
所以利用好索引&#xff0c;即使面对百万、千万、上亿条数据也不用担心查询超时。