获取两个时间戳之间的所有行

时间:2013-11-27 19:32:35

标签: mysql

我很难让这种逻辑恰到好处。我需要获取两个unix时间戳之间匹配的所有行。

在此示例中,预订#1已存在于数据库中。预订#2的时间应该已经从预订#1返回了数据,但它没有那样工作。

有人能告诉我哪里出错了吗?

booking #1 start = 1385546460 = 11 / 27 / 13 @ 10:01:00am UTC
booking #1 stop  = 1385593140 = 11 / 27 / 13 @ 10:59:00pm UTC

booking #2 start = 1385560860 = 11 / 27 / 13 @ 2:01:00pm UTC
booking #2 stop  = 1385567940 = 11 / 27 / 13 @ 3:59:00pm UTC

SELECT
  t1.start
, t1.stop
, t1.booking_id
FROM booking AS t1
WHERE t1.location_id = 1 AND
(t1.start BETWEEN '1385560860' AND '1385567940' OR t1.stop  BETWEEN '1385560860' AND '1385567940')

1 个答案:

答案 0 :(得分:0)

预订1从大约10:00 - 22:00开始,预订2从14:00 - 16:00开始,因此预订1的结尾当然不会在预订2的两端之间出现。

我认为你想要计算封闭间隔的重叠:

WHERE t1.start <= t2.stop
      AND
      t1.stop  >= t2.start

这种表述将与人们通常认为的方式重叠。如下图所示,它会发现A,B,C和D与“Window”重叠,但E和F不重叠。

(time) ==========================>

Window:      |-------|
     A: |-----|
     B:        |--|
     C:   |------------|
     D:          |-------|
     E:  |-|
     F:                 |-----|