SQL中使用日期函数后WHERE子句过滤失效问题排查
问题解决:WHERE子句过滤timestamp字段不生效
你的问题出在字符串日期格式与数据库默认解析规则不匹配:lasttime是timestamp类型,当你直接用<= '10/28/2022'作为条件时,数据库会按照自身默认的日期格式(多数数据库默认是yyyy-MM-dd)去解析这个字符串,10/28/2022不符合该格式,导致数据库无法正确识别,最终过滤条件失效。
解决方法
方法1:使用数据库函数将字符串转换为合法日期类型
根据你使用的数据库,选择对应的转换函数:
- MySQL:
select rule, weight, date(lasttime) as last_date_fired from prod_frm.rules_recent where lasttime <= STR_TO_DATE('10/28/2022', '%m/%d/%Y') limit 2000;
- PostgreSQL:
select rule, weight, date(lasttime) as last_date_fired from prod_frm.rules_recent where lasttime <= TO_DATE('10/28/2022', 'MM/DD/YYYY') limit 2000;
- SQL Server:
select rule, weight, date(lasttime) as last_date_fired from prod_frm.rules_recent where lasttime <= CONVERT(DATE, '10/28/2022', 101) limit 2000;
方法2:直接使用数据库默认识别的标准日期格式
把日期字符串改成yyyy-MM-dd格式,数据库能自动解析:
select rule, weight, date(lasttime) as last_date_fired from prod_frm.rules_recent where lasttime <= '2022-10-28' limit 2000;
内容的提问来源于stack exchange,提问作者arthomp3
相关产品推荐
相关产品推荐

