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

Mysql如何筛选有效期内优惠:到期日为NULL/空时始终展示

有效期优惠活动筛选SQL修正方案

筛选规则

  • 当前时间晚于等于活动开始时间
  • 若活动到期日期非空且不为NULL,当前时间需早于到期时间
  • 若到期日期为NULL或空值,活动始终可展示

现有SQL核心问题

  1. 逻辑运算符优先级错误:MySQL中AND运算优先级高于OR,原语句的到期时间为空判断会直接绕过前面的活动状态、开始时间校验,只要到期时间为空就会被查询出来,不符合筛选要求
  2. 开始时间判断逻辑反向:原条件deals.deal_start >= 当前时间是筛选还未开始的活动,和要求的「当前时间晚于等于活动开始时间」逻辑相反

表结构

deal_titledeal_startdeal_expire
Example Deal10-24-2021 16:10:0010-25-2021 16:10:00
Example Deal 210-24-2021 16:10:00NULL

按时区获取当前时间的PHP函数

function getDateByTimeZone(){
   $date = new DateTime("now", new DateTimeZone("Europe/London") );
   return $date->format('m-d-Y H:i:s');
}

修正后的MySQL查询语句

SELECT deals.*, categories.category_title AS category_title 
FROM deals 
LEFT JOIN categories ON deal_category = categories.category_id 
WHERE deals.deal_status = 1 
 AND deals.deal_featured = 1 
 AND '" . getDateByTimeZone() . "' >= deals.deal_start
 AND (
    '" . getDateByTimeZone() . "' < deals.deal_expire 
    OR deals.deal_expire IS NULL 
    OR deals.deal_expire = ''
 )
GROUP BY deals.deal_id ORDER BY deals.deal_created DESC

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 12:15:06