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

Sequelize查询中<=条件未生效,无法获取当日数据的问题

问题原因及解决办法

核心原因

你使用的endDate如果是'YYYY-MM-DD'这类纯日期字符串,数据库会自动将其解析为当天的零点时刻(比如'2024-05-20 00:00:00')。但wish_lists表中20日创建的数据,created_at字段是带时分秒的完整时间(比如'2024-05-20 10:30:00'),这个时间明显大于当天零点,自然不会被<= '2024-05-20'的条件匹配到。

两种可行的修复方案

方案一:用次日零点做小于判断(推荐)

把查询条件改成wl.created_at < 次日零点,这样就能完整覆盖endDate当天的所有数据。

在Node.js里可以这样生成次日零点的字符串:

const endDateObj = new Date(endDate);
// 加一天得到次日
endDateObj.setDate(endDateObj.getDate() + 1);
// 格式化为YYYY-MM-DD格式
const nextDayStr = endDateObj.toISOString().split('T')[0];

对应的SQL条件修改为:

wl.created_at >= '${startDate}' AND wl.created_at < '${nextDayStr}'

方案二:给endDate拼接当天的最后一秒

直接把endDate加上' 23:59:59',让条件覆盖到当天的最后一刻:

wl.created_at >= '${startDate}' AND wl.created_at <= '${endDate} 23:59:59'

注意:如果你的created_at字段是高精度时间(带毫秒),那23:59:59.999的数据还是会被漏掉,所以方案一更稳妥。

重要提醒:防范SQL注入

你现在直接把变量拼进SQL字符串的写法存在SQL注入风险,建议改用Sequelize的参数绑定方式:

const [results] = await sequelize.query(`
select DISTINCT ON (variant_id) variant_id, Count(wl) as count, pds.name AS name,
  CASE
      WHEN pvs.name is NULL THEN pds.name
      ELSE pvs.name
  END 
  as variant_name,
  im.url as img_url
from wish_lists as wl
LEFT JOIN products AS pds ON pds.id = wl.product_id
LEFT JOIN images as im on im.product_id = wl.product_id
LEFT JOIN product_variants as pvs ON pvs.id = wl.variant_id
where wl.created_at >= :startDate AND wl.created_at < :nextDayStr AND wl.tenant_id=:merchantId
group by ( variant_id, pds.name, im.url, pvs.name) LIMIT 100 OFFSET 0`, {
  replacements: {
    startDate,
    nextDayStr,
    merchantId: merchant_id
  }
});

内容的提问来源于stack exchange,提问作者Alexander Solonik

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 11:56:34