2017-04-25 80 views
0

enter image description hereMySQL查詢有或無日期

我想基於今天日期開始和截止日期列,即使是不具有日期值的行來選擇行選擇行。所以

$query=mysql_query("SELECT * FROM discounts where '".date('Y-m-d')."' >= coupon_start_date AND '".date('Y-m-d')."' <= coupon_expiry_date 
UNION SELECT * FROM ecwid_discounts where '".date('Y-m-d')."' >= coupon_start_date AND coupon_expiry_date is NULL union SELECT * FROM ecwid_discounts where coupon_start_date is NULL AND '".date('Y-m-d')."' <= coupon_expiry_date union SELECT * FROM ecwid_discounts where coupon_start_date is NULL AND coupon_expiry_date is null"); 

我想確認,如果該查詢是正確的還是有改寫總之這個查詢的任何更好的辦法。

任何幫助球員

+2

** WARNING **:如果你剛開始學習PHP,請不要學過時['mysql_query'(HTTP: //php.net/manual/en/function.mysql-query.php)界面。這很糟糕,並且已經在PHP 7中被刪除了。像[PDO不是很難學的東西](http://net.tutsplus.com/tutorials/php/why-you-should-be-using-php-pdo- for-database-access /)以及[PHP The Right Way](http://www.phptherightway.com/)等指南有助於解釋最佳實踐。確保**你的用戶參數[妥善轉義](http://bobby-tables.com/php),否則你將以嚴重的[SQL注入漏洞](http://bobby-tables.com/ )。 – tadman

+1

你可以使用'OR',所以你不需要'UNION'。 –

回答

0

使用此查詢:

$query=mysql_query("SELECT * FROM discounts where '".date('Y-m-d')."' >= coupon_start_date AND '".date('Y-m-d')."' <= coupon_expiry_date 
UNION SELECT * FROM ecwid_discounts where '".date('Y-m-d')."' >= coupon_start_date AND '".date('Y-m-d')."' <= coupon_expiry_date OR '".date('Y-m-d')."' >= coupon_start_date AND coupon_expiry_date is NULL OR coupon_start_date is NULL AND '".date('Y-m-d')."' <= coupon_expiry_date OR coupon_start_date is NULL AND coupon_expiry_date is null");