MYSQL:使用多个日期和日期范围进行过滤

时间:2018-12-20 00:16:22

标签: mysql sql

我有2个日期要按2个日期过滤。

我的桌子上有这些数据

id  date_from    date_to     name
1   2018-10-11   2018-10-25  LeBron James
2   2018-10-11   2018-10-25  Stephen Curry
3   2018-10-26   2018-11-10  Kevin Durant

我想做的是根据给定的日期范围对其进行过滤。 所以如果我有2个日期(2018-10-01至2018-10-22)。我只会看到ID 1和ID 2,如果有(2018-10-12至2018-10-31),我将显示所有数据。

我的示例代码 我使用范围的开始和结束

 SELECT * FROM table WHERE (date_from BETWEEN @start AND @end) OR (date_to BETWEEN @start AND @end)

// 问题在于,如果在范围内找不到值,它将显示所有内容。

 SELECT * FROM table WHERE (date_from >= @start AND date_from <= @end) AND (date_to >= @start AND date_to <= @end)

// 问题-没有数据会出现

我该怎么办,我对很多约会感到困惑。

2 个答案:

答案 0 :(得分:3)

我认为你想要和重叠。如果是这样:

SELECT t.*
FROM table
WHERE t.date_from <= @end AND
      t.date_to >= @start;

如果一个周期在第二周期结束之前开始,反之亦然。两个周期重叠。

答案 1 :(得分:3)

这可能有助于阐明:

  @start    @end
s-E |        |        ignore (starts & ends before the period)

 s--|--------|-E      spans the period
  s-|---E    |        start before, but ends in, the period
    s----E   |        starts at beginning of the period, finishes before the period ends
    | s---E  |        starts and finished within the period
    |   s----E        starts within the period, finishes on last day of the period
    |     s--|-E      starts within the period but finishes after the period

    |        | s-E    ignore (starts & ends after the period)

 for those we want s is always <= @end
 for those we want E is always >= @start

将起点与终点进行比较似乎是违反直觉的,反之亦然,但是由于试图显示较小的图形,因此这是最一致的关系。