开始日期和结束日期查询无效

时间:2013-11-29 06:38:39

标签: java php mysql .net sql

以下是要求

如果搜索日期范围是2013年5月15日到2013年5月21日,那么将包含或排除具有以下事件日期范围的事件:

1/01/2013 to 6/30/2013 include
2/15/2013 to 3/15/2013 exclude
5/01/2013 to 5/19/2013 include
5/01/2013 to 5/14/2013 exclude
5/15/2013 to 5/15/2013 include
5/21/2013 to 5/21/2013 include
5/17/2013 to 5/30/2013 include
5/16/2013 to 5/20/2013 include
5/22/2013 to 5/30/2013 exclude
*5/16/2013 to 00/00/0000 include
5/22/2013 to 00/00/0000 exclude*

以下是我所做的查询,但不符合上述条件

SELECT cm_id,cm_date_from,cm_date_to FROM Cat_Master
WHERE TRUE  AND ( "2013-05-15" BETWEEN cm_date_from AND cm_date_to OR "2013-05-21" BETWEEN cm_date_from AND cm_date_to
    OR "2013-05-15" >= cm_date_from AND "2013-05-21" <= cm_date_to   OR "2013-05-15" <= cm_date_from AND "2013-05-21" >= cm_date_to
    )

请指导以上查询 感谢

3 个答案:

答案 0 :(得分:0)

  

TO_DATE(string1,[format_mask],[nls_language])

TO_DATE('2013-05-15,'yyyy-mm-dd')。

日期比较使用日期变量。

P.S:我认为你使用的是Oracle Db(因为你没有提到)

答案 1 :(得分:0)

在第2和第3 OR运营商之后,您似乎错过了支持 试试这个:

SELECT cm_id,cm_date_from,cm_date_to
FROM Cat_Master
WHERE TRUE  AND ( 
  "2013-05-15" BETWEEN cm_date_from AND cm_date_to
  OR
  "2013-05-21" BETWEEN cm_date_from AND cm_date_to
  OR
  ( "2013-05-15" >= cm_date_from AND "2013-05-21" <= cm_date_to )
  OR
  ( "2013-05-15" <= cm_date_from AND "2013-05-21" >= cm_date_to )
    )

答案 2 :(得分:0)

使用日期类型来比较日期。

  WHERE ( to_date('2013-05-15','YYYY-MM-DD') BETWEEN cm_date_from AND cm_date_to OR 
  to_date('2013-05-21','YYYY-MM-DD') BETWEEN cm_date_from AND cm_date_to
  OR to_date('2013-05-15','YYYY-MM-DD') >= cm_date_from AND to_date('2013-05-21','YYYY-MM-DD') <= 
  cm_date_to   OR to_date('2013-05-15','YYYY-MM-DD') <= cm_date_from AND 
to_date('2013-05-21','YYYY-MM-DD') >= cm_date_to  );