【问题标题】:Filter products by price按价格筛选产品
【发布时间】:2017-04-19 07:25:18
【问题描述】:

我正在尝试按价格过滤产品,但遇到了特价问题。
如果特价适用于产品,则以下查询显示随机结果。

"SELECT * FROM tablename WHERE ((price >= ".(int)$min_price." AND price <= ".(int)$max_price." AND ('".date('Y-m-d')."' NOT BETWEEN special_price_startdate AND special_price_enddate OR special_price_startdate = NULL OR special_price_enddate= NULL)) OR (('".date('Y-m-d')."' BETWEEN special_price_startdate AND special_price_enddate AND special_price_startdate IS NOT NULL AND special_price_enddate IS NOT NULL) AND special_price >= ".(int)$min_price." AND special_price <= ".(int)$max_price.")) AND isactive = 1 AND isdeleted = 0 ORDER BY created DESC, productid DESC LIMIT ".(($page-1)*$perpage).",".$perpage;

【问题讨论】:

  • 如果您能告诉我们您期望的结果和实际得到的结果,我们会更容易提供帮助!

标签: php sql filter


【解决方案1】:

查询完全按照它的语法做它应该做的事情:如果特价适用并且特价在设置的限制之间,它返回该行。否则,如果特价不适用且正常价格在设置的限制之间,则返回该行:

CREATE TABLE `tablename` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `price` int(11) DEFAULT NULL,
  `special_price_startdate` date DEFAULT NULL,
  `special_price_enddate` date DEFAULT NULL,
  `isactive` bit(1) DEFAULT NULL,
  `isdeleted` bit(1) DEFAULT NULL,
  `special_price` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

针对 PHP 输入调整查询:

SELECT *
  FROM tablename
 WHERE     (   (    price >= 99
                AND price <= 999
                AND (   '2017-04-21' NOT BETWEEN special_price_startdate
                                             AND special_price_enddate
                     OR special_price_startdate = NULL
                     OR special_price_enddate = NULL))
            OR (    (    '2017-04-21' BETWEEN special_price_startdate
                                          AND special_price_enddate
                     AND special_price_startdate IS NOT NULL
                     AND special_price_enddate IS NOT NULL)
                AND special_price >= 99
                AND special_price <= 999))
       AND isactive = 1
       AND isdeleted = 0
/*ORDER BY created DESC, productid DESC*/
 LIMIT 10;

插入种子数据:

INSERT INTO `tablename` values
(1, 120, '2017-04-20', '2017-04-22', 1, 0, 125), 
(2, 125, '2017-04-27', '2017-04-28', 1, 0, 125), 
(3, 120, '2017-04-20', '2017-04-22', 1, 0, 50), 
(4, 50, '2017-04-27', '2017-04-28', 1, 0, 125)

输出:

1   120 4/20/2017 12:00:00 AM   4/22/2017 12:00:00 AM   1   0   125
2   125 4/27/2017 12:00:00 AM   4/28/2017 12:00:00 AM   1   0   125

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-28
    • 1970-01-01
    • 2013-01-24
    • 2014-04-15
    • 2018-04-26
    • 2020-11-12
    • 1970-01-01
    • 2015-03-24
    相关资源
    最近更新 更多