Select 行在 where 子句中计算了持续时间

Select rows with duration calculation in the where clause

我需要了解如何 COUNT 匹配我的查询的行数。这是我的数据库:

+----+---------------+---------------+----------+
| id | delivery_date | delivery_time | duration |
+----+---------------+---------------+----------+
| 1  | 2018-02-17    | 10:30:00      | 40       |
+----+---------------+---------------+----------+
| 2  | 2018-02-18    | 14:20:00      | 25       |
+----+---------------+---------------+----------+
| 3  | 2018-02-19    | 08:50:00      | null     |
+----+---------------+---------------+----------+

我有一个 selectedDate 和一个 selectedTime。我想看看是不是在"duration"期间,前后

因此,例如,如果 delivery_time10:30:00 并且 duration 是 40,那么它会减去 40 并在 delivery_time 上加上 40。因此,任何介于 09:50:00 - 11:10:00 之间的时间都将被计为存在。

此外,如果持续时间不存在或为空,则只会计算 delivery_time 本身。

这是我的代码(只是一个例子,不是生产安全的,包含漏洞):

/////// Expected Output //////

$selectedDate1 = '2018-02-18';
$selectedTime1 = '14:35:00';
// Exists


$selectedDate2 = '2018-02-18';
$selectedTime2 = '14:50:00';
// Does not exist


$selectedDate3 = '2018-02-17';
$selectedTime3 = '09:50:00';
// Exists


$selectedDate3 = '2018-02-19';
$selectedTime3 = '08:50:00';
// Exists

////// Expected Output End //////


$stmt = $dbh->prepare("
    SELECT COUNT(*) FROM deliveries
    WHERE delivery_date = $selectedDate# AND
    (delivery_time = $selectedTime# AND duration IS NULL)
    OR
    (delivery_time +-= duration = $selectedTime# AND duration IS NOT NULL)
);

显然 delivery_time +-= duration 需要 fixed/revised。任何帮助将不胜感激!

此查询将为您提供所需的结果。它检查交货日期是否与 selected 日期匹配,然后检查交货时间是否与 select 时间相同(不需要检查是否 duration IS NULL也是 duration IS NOT NULL 时的有效条件),或者如果 selected 时间在交付范围内 window(delivery_time +/- 持续时间)。

SELECT COUNT(*)
FROM deliveries
WHERE delivery_date = @selectedDate
  AND (delivery_time = @selectedTime OR
       @selectedTime BETWEEN delivery_time - INTERVAL duration MINUTE
                         AND delivery_time + INTERVAL duration MINUTE);

Demo on dbfiddle