You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 18:40:43