我试图按价格过滤产品,但遇到特价的问题 如果特殊价格适用于产品,则查询显示随机结果。
"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;
答案 0 :(得分:0)
查询根据其语法完全按照它应该执行的操作:如果特殊价格适用且特殊价格在设置限制之间,则返回行。否则,如果特殊价格不适用且常规价格在设定限额之间,则返回行:
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