oracle日期类型字段使用like匹配的问题
场景:经常需要通过卡日期字段来统计数据量或指标,实际开发中是使用like匹配时,无法匹配到数据的问题。
原因:在 Oracle 数据库中,日期函数本身不支持 LIKE 匹配,因为 LIKE 是用于字符串匹配的。但是,你可以通过将日期转换为字符串,然后使用 LIKE 进行匹配
1.样例数据如下(create_time是日期类型且加了索引):
select pno,create_time from test_01 t;
-------------------------------------------------------------
| PNO | CREATE_TIME |
-------------------------------------------------------------
| 3000446 | 2003-04-17 00:00:00.0 |
| 3000446 | 2003-04-17 00:00:00.0 |
| 3000446 | 2004-02-25 17:02:18.0 |
| 3000446 | 2003-04-17 00:00:00.0 |
| 3000446 | 2004-02-25 17:02:18.0 |
| 3000446 | 2004-07-19 16:11:45.0 |
-------------------------------------------------------------
2.create_time 是日期类型,直接对改字段使用like匹配失败
select pno,create_time from test_01 t
where create_time like '2003-04-17%';
-------------------------------------------------------------
| PNO | CREATE_TIME |
-------------------------------------------------------------
-------------------------------------------------------------
3.create_time 是日期类型,先转成字符串之后,使用like匹配成功
#使用该方式走不了索引,查询性能不佳
select pno,create_time from test_01 t
where to_char(create_time,'yyyymmdd') like '%20030417%';
-------------------------------------------------------------
| PNO | CREATE_TIME |
-------------------------------------------------------------
| 3000446 | 2003-04-17 00:00:00.0 |
| 3000446 | 2003-04-17 00:00:00.0 |
| 3000446 | 2003-04-17 00:00:00.0 |
-------------------------------------------------------------
4.create_time不做处理,可以使用到索引
#推荐使用该方式
select pno,create_time from test_01 t
where create_time >= to_date('2003-04-17','yyyy-mm-dd') and create_time < to_date('2003-04-18','yyyy-mm-dd');
-------------------------------------------------------------
| PNO | CREATE_TIME |
-------------------------------------------------------------
| 3000446 | 2003-04-17 00:00:00.0 |
| 3000446 | 2003-04-17 00:00:00.0 |
| 3000446 | 2003-04-17 00:00:00.0 |
-------------------------------------------------------------