PHP Mysql在时间范围之间获得差距

时间:2016-02-25 06:35:19

标签: php mysql time difference-between-rows

我在stackoverflow中有点新鲜。无论如何这里是我的问题,希望有人可以帮助我。 我在mysql中有一个表见下面

Start Time         End Time         Date
 9:00               10:00           2016-02-26
 9:00               10:00           2016-02-25
 11:00              12:00           2016-02-25
 12:00              13:00           2016-02-25
 13:00              14:00           2016-02-25
 15:00              16:00           2016-02-25

我想得到的是这些时间与特定日期之间的差距。请参阅下面的我想要的输出:

Start Time         End Time        Date
 10:00               11:00         2016-02-25
 14:00               15:00         2016-02-25

如果有人知道答案,那将是一个很大的帮助。感谢

1 个答案:

答案 0 :(得分:1)

您可以使用以下查询:

SELECT gap_start, gap_end
FROM (
  SELECT (SELECT EndTime
         FROM mytable AS t2
         WHERE t2.EndTime < t1.StartTime
         ORDER BY t2.EndTime DESC LIMIT 1) AS gap_start,
         StartTime AS gap_end
  FROM mytable AS t1) AS t
WHERE gap_start IS NOT NULL

使用的相关子查询将获取紧接在当前记录之前的记录的StartTime。这里假设总是连续记录之间的间隙。

Demo here

修改

可以按如下方式修改查询,以便处理Date字段的添加:

SELECT gap_start, gap_end, `Date`
FROM (
  SELECT (SELECT EndTime
          FROM mytable AS t2
          WHERE t2.`Date` <= t1.`Date` AND t2.EndTime <= t1.StartTime
          ORDER BY t2.`Date` DESC, t2.EndTime DESC LIMIT 1) AS gap_start,
         StartTime AS gap_end,
         `Date`
  FROM mytable AS t1) AS t
WHERE gap_start IS NOT NULL AND gap_start < gap_end

Demo here