【问题标题】:Checking if time equals a time with duration检查时间是否等于带持续时间的时间
【发布时间】:2019-04-18 19:23:11
【问题描述】:

所以我正在创建一个送餐系统。我想检查一下,是否需要时间。问题是存在与某些时间相关的持续时间。如果没有持续时间,这很容易做到。

工作代码示例:

例如,这是我的deliveries 表:

+----+---------------+---------------+----------+
| id | delivery_date | delivery_time | duration |
+----+---------------+---------------+----------+
| 1  | 2018-02-18    | 10:30:00      | null     |
+----+---------------+---------------+----------+

假设我选择的交货时间是2018-02-18 10:30:00,那么它将被采取。代码是:

$deliveryDate = '2018-02-18';
$deliveryTime = '10:30:00';

$stmt = "SELECT id FROM deliveries WHERE appointment_date = :date AND appointment_time = :time";
$stmt->bindParam(':date', $deliveryDate);
$stmt->bindParam(':time', $deliveryTime);
$stmt->execute();
$result = $stmt->fetch();

if($result) {
    echo 'Sorry, this is already taken!';
}

该代码正在运行。


不工作的代码示例:

我正在尝试确定是否将 durationnull 更改为 40(40 分钟),它需要阻止 2018-02-18 10:30:00 to 11:10:00

假设持续时间为 40(分钟),delivery_time11:05:00。它应该阻止它。

+----+---------------+---------------+----------+
| id | delivery_date | delivery_time | duration |
+----+---------------+---------------+----------+
| 1  | 2018-02-18    | 10:30:00      | 40       |
+----+---------------+---------------+----------+

$deliveryDate = '2018-02-18';
$deliveryTime = '11:05:00';

$stmt = "SELECT id FROM deliveries WHERE appointment_date = :date AND appointment_time = :time";
$stmt->bindParam(':date', $deliveryDate);
$stmt->bindParam(':time', $deliveryTime);
$stmt->execute();
$result = $stmt->fetch();

if($result) {
    echo 'Sorry, this is already taken!';
}

如何让它考虑持续时间?

【问题讨论】:

  • 到目前为止你尝试过什么?似乎是设置最小(delivery_time)和最大(加上duration)时间的简单案例。

标签: php mysql mysqli time pdo


【解决方案1】:

如果您将日期和时间列组合到datetime,您可以使用timestampadd() 添加持续时间,然后检查给定的日期和时间是否在该时间段内。

SELECT id
       FROM deliveries
       WHERE cast(concat(delivery_date, ' ', delivery_time) AS datetime) <= cast(concat(:date, ' ', :time) AS datetime)
             AND timestampadd(minute, duration, cast(concat(delivery_date, ' ', delivery_time) AS datetime)) > cast(concat(:date, ' ', :time) AS datetime);

db<>fiddle

如果您只在此处使用两个 datetimes 而不是将其分成三列,您可以让您的生活更轻松。然后你也可以从索引中受益。

【讨论】:

  • 失去使用索引的可能性(如果它们当然存在的话)在性能方面可能是一件相当大的事情。
猜你喜欢
  • 2017-04-08
  • 2016-09-30
  • 2012-07-03
  • 2021-08-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多