mysql:具有多个日期和日期范围的过滤器

vhmi4jdf  于 2021-06-15  发布在  Mysql
关注(0)|答案(2)|浏览(357)

我有两个日期要被两个日期过滤。
我桌上有这些数据

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

我想做的是根据给定的日期范围对其进行过滤。如果我有两个日期(2018-10-01到2018-10-22)。我只会看到id 1和2,如果有(2018-10-12到2018-10-31),我会显示所有数据。
我的示例代码使用了范围的start和end

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)

//问题-不会出现任何数据
我该怎么办,我被很多约会弄糊涂了。

bzzcjhmw

bzzcjhmw1#

我想你想要和重叠。如果是:

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

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

acruukt9

acruukt92#

这可能有助于澄清:

@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

把起点和终点进行比较似乎有悖常理,反之亦然,但当这个小图形试图显示时,它是最一致的关系。

相关问题