坑描述:sql
公司的订单表数据量巨大(亿级),在进行查询的时候,发现一个慢查询。数据库
背景:mybatis
数据库:oracleoracle
表:T_order 函数
索引字段:create_date (字段类型 date)spa
慢查询sql:索引
select * from T_order where create_date >= #{parameterDate}ast
慢查询的缘由:date
若是JAVA中的属性为DATE,而数据库中是DATE类型的话,mybatis会默认将JAVA中DATE属性映射到数据库的Timestamp类型。此时字段 create_date 为date类型,参数parameterDate为timestamp类型,二者的类型不一致。oracle数据库会date类型转换为timestamp类型(精确度小的类型转换为精确度大的类型),所以实际执行的sql语句为:select * from T_order where to_timestamp(create_date ) >= #{parameterDate} 致使左边的列用到函数。即索引列上使用函数后会致使索引失效,这样一来就全表扫描了订单库,形成慢sql。select
解决方法:
缘由以及知道了,解决起来就容易了。
修改后的sql为:
select * from T_order where create_date >= cast(#{parameterDate} as date)
注意的点:
一、索引的使用。
二、MyBatis的类型转换。
三、oracle的类型转换。
四、to_timestamp(将date类型转换为Timestamp类型),cast(将某种数据类型的表达式显式转换为另外一种数据类型,在此将Timestamp转换为date类型)这两个函数的使用。