获取两个日期之间的所有日期,即使不存在查询跳过范围内的现有记录

时间:2018-03-11 22:19:48

标签: php mysql datetime

我有一个数据库表,我需要在两个日期(甚至是不存在的日期)之间获取所有日期,其中查询将跳过与集合中的任何日期匹配的那些记录。

示例:

Start date: 2018-03-11 00:00:00
End date: 2019-03-11 00:00:00
Interval: 1 month

在数据库中我有两条记录:

2018-03-11 00:00:00 and 2018-04-11 00:00:00

结果如下:

2018-05-11 00:00:00 through 2019-03-11 00:00:00

我们看到结果省略了第一个2018-03-11 00:00:00和第二个2018-04-11 00:00:00记录,但打印出其余记录。

我很高兴有人可以给我一些指导。

我试图在PHP的一半MySQL中实现一些东西但是本地化的日期格式化只带来了噩梦。我在PHP中使用这样的东西:

public function getDateRange($start, $end, $interval, $type)
{
    if ($type === 'month') {
        $interval = new DateInterval('P' . $interval . 'M');
    } elseif ($type === 'day') {
        $interval = new DateInterval('P' . $interval . 'D');
    } elseif ($type === 'year') {
        $interval = new DateInterval('P' . $interval . 'Y');
    }

    $start = new DateTime($start, $this->serverTimezone);
    $end = new DateTime($end, $this->serverTimezone);
    $period = new DatePeriod($start, $interval, $end);

    $result = [];

    foreach ($period as $date) {
        $result[] = $date->format($this->datetimeFormat);
    }

    return $result;
}

数据库表结构:

CREATE TABLE `es_servicepayment` (
`servicepayment_id` int(11) UNSIGNED NOT NULL,
`servicepayment_amount` decimal(11,3) UNSIGNED NOT NULL,
`servicepayment_interval` tinyint(3) UNSIGNED NOT NULL,
`servicepayment_type` enum('day','month','year') COLLATE utf8mb4_unicode_ci NOT NULL,
`paymenttype_id` int(11) UNSIGNED NOT NULL,
`servicepayment_added` datetime NOT NULL,
`servicepayment_updated` datetime NOT NULL,
`service_id` int(11) UNSIGNED NOT NULL,
`user_id` int(11) UNSIGNED NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

表格数据:

INSERT INTO `es_servicepayment` (`servicepayment_id`, `servicepayment_amount`, `servicepayment_interval`, `servicepayment_type`, `paymenttype_id`, `servicepayment_added`, `servicepayment_updated`, `service_id`, `user_id`) VALUES
(1, '23.000', 1, 'month', 1, '2018-03-11 00:00:00', '2018-03-11 00:00:00', 1, 1),
(2, '23.000', 1, 'month', 1, '2018-04-11 00:00:00', '2018-04-11 00:00:00', 1, 1);

我需要这样的东西:

2018-05-11 00:00:00
2018-06-11 00:00:00
2018-07-11 00:00:00
2018-08-11 00:00:00
2018-09-11 00:00:00
2018-10-11 00:00:00
2018-11-11 00:00:00
2018-12-11 00:00:00
2019-01-11 00:00:00
2019-02-11 00:00:00
2019-03-11 00:00:00

除已存储在数据库中的日期外:

2018-03-11 00:00:00
2018-04-11 00:00:00

1 个答案:

答案 0 :(得分:0)

没关系。案件已经解决。它的工作方式是我从数据库中选择已存储的日期,然后在PHP中生成日期范围,然后我在两个数组上执行array_diff(),这样结果只包含数据库中不存在的日期。