我需要一个帮助我无法使用PHP和MySQL根据某些条件从表中获取值。我在解释下表。
数据库子目录:

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 !='')的条目时,我无法获取值。
1 -如果from_date and to_date具有值,如果存在值,则匹配。
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

注意这个GROUP BY子句在除MySQL之外的所有DBMS中都是无效的。您不应该使用SELECT *语句来实现这一点,应该始终指定列,并且每一列都应该在GROUP BY子句中,或者用一个聚合函数包装起来。

10-05 21:04
查看更多