SQL:按日期范围查找数据

时间:2018-05-18 04:32:01

标签: mysql sql

我有2条记录,字段为“from_date”和“to_date”:

client

如果从日期搜索,如何获取记录2:

 - Record 1 : from_date=2017-05-15 and to_date=2017-06-12
 - Record 2 : from_date=2018-03-20 and to_date=2018-04-11

 - 2018-03-01 and 2018-03-31?

 - 2018-04-01 and 2018-04-30?

4 个答案:

答案 0 :(得分:0)

这很简单:

SELECT * 
   FROM records 
    WHERE from_date >= @from_date 
         OR to_date <= @to_date 

@from_date@to_date只是你的变量。

我使用了OR,因为您没有寻找包容性范围。这只是部分匹配。

您想要一个与此记录from_date=2018-03-20to_date=2018-04-11

匹配的条件

让我们根据WHERE from_date >= @from_date OR to_date <= @to_date

查看条件
@from_date = 2018-03-01 --false
@to_date   = 2018-03-31 --true
--
@from_date = 2018-04-01 --true
@to_date   = 2018-04-30 --false
--
@from_date = 2018-04-01 --true
@to_date   = 2018-04-03 --true

这表明你只需要一个bounderies来匹配。

请注意,基于DBMS,日期比较可能会有所不同,但逻辑保持不变。

答案 1 :(得分:0)

试试这个样本:

Declare @date1 Date
Declare @date2 Date

set @date1 = <<give your first date>> 'yyyy-dd-mm
set @date2 = <<give your second date>> 'yyyy-dd-mm

SELECT * FROM tbldate WHERE CONVERT(DATE,@date1) BETWEEN from_date and to_date OR CONVERT(DATE,@date2) BETWEEN from_date and to_date

答案 2 :(得分:0)

oracle示例:

with 
    table1 as 
      ( select 1 id, to_date('2017-05-15','YYYY-MM-DD') date_from, to_date('2017-06-12','YYYY-MM-DD') date_to  from dual union all
        select 2 id, to_date('2018-03-20','YYYY-MM-DD') date_from, to_date('2018-04-11','YYYY-MM-DD') date_to  from dual )
select
    *
from 
    table1
where
/*
        to_date('2018-03-01','YYYY-MM-DD') < date_to
    and to_date('2018-03-31','YYYY-MM-DD') > date_from

        to_date('2018-04-01','YYYY-MM-DD') < date_to
    and to_date('2018-04-30','YYYY-MM-DD') > date_from
*/
        to_date('2018-04-01','YYYY-MM-DD') < date_to
    and to_date('2018-04-03','YYYY-MM-DD') > date_from
;

答案 3 :(得分:0)

谢谢大家的回复。我找到了答案。

WHERE ((from_date BETWEEN {fromDate} AND {toDate} OR to_date BETWEEN {fromDate} AND {toDate} OR (from_date <= {fromDate} AND to_date >= {fromDate}))

如果使用CakePHP3:

->where([
        'OR' => [
            function($exp) use($fromDate,$toDate){                            
                return $exp->between('from_date',$fromDate,$toDate,'date');
            },
            function($exp) use($fromDate,$toDate){                            
                return $exp->between('to_date',$fromDate,$toDate,'date');
            }, 
            'AND' => [
                'from_date <=' => $fromDate,
                'to_date >=' => $fromDate
            ]
        ],
        'from_date is not' => null
    ]);