2017-04-19 313 views
-1

我想按價格過濾產品,但遇到了特殊價格的問題。
如果特殊價格適用於產品比以下查詢顯示隨機結果。按價格過濾產品

"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; 
+1

如果您能告訴我們您期望得到的結果以及您實際得到的結果,它會使幫助更容易! – RobFos

回答

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