簡體   English   中英

MySQL比較日期不返回結果

[英]MySQL comparing dates doesn't return results

我需要一個幫助。 根據某些條件,我無法使用PHP和MySQL從表中獲取值。 我正在解釋下面的表格。

db_subcat:

id    subcat_id   sub_name      from_date       to_date
------------------------------------------------------------
1       60          Ram         2016-10-25       2016-10-28
2       60          Ram                                    
3       61          Raj                                 

這里有些行沒有from_date and to_date值。我在下面解釋我的查詢。

$date="2016-10-23";
$sql="select * from db_subcat 
    where from_date <='".$date."' and to_date >= '".$date."' and from_date !='' and to_date !='' 
    group by subcat_id 
    union all select * from db_basic 
    where from_date ='' and to_date ='' 
    group by sucat_id";

這是我的問題是我無法獲取值,而表沒有(from_date ='' and to_date ='')(from_date !='' and to_date !='')這里我需要使用all來獲取值以下條件。

1-如果from_date and to_date具有值,並且如果value存在,則它將匹配。

2-如果from_date and to_date具有值或兩個條件值都為空白,則應獲取。

3-如果表沒有(from_date ='' and to_date ='')(from_date !='' and to_date !='')

請幫助我解決此問題。

如果我對您的理解正確,則可能需要使用ISNULL並且可以將兩個查詢結合使用:

select * from db_subcat
where ((from_date IS NULL OR from_date ='') AND (to_date IS NULL OR to_date =''))
   OR (from_date <='".$date."' and to_date >= '".$date."') 
group by subcat_id

請注意,除了MySQL之外,此GROUP BY子句在所有DBMS中均無效。 您不應使用SELECT *語句來執行此操作,而應始終指定列,並且每一列都應位於GROUP BY子句中,或者應使用環繞其的聚合函數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM