加入两个条目之间的日期

时间:2016-03-22 16:31:56

标签: mysql

我有以下两个表:

DELIVERY as t1

date,               driver_id

2016-01-01 13:44:22, 32
2016-01-02 13:14:58, 32
2016-03-05 13:14:55, 32

DELIVERY表有交货提货时的记录。

DRIVER_DISPATCH_HISTORY as t2

date,               driver_id, dispatch_id

2016-01-01 19:12:23, 32,        4
2016-01-07 11:16:58, 32,        3
2016-03-06 13:14:55, 32,        7
2016-03-06 16:54:12, 33,        8

DRIVER_DISPATCH_HISTORY表跟踪何时分配了驱动程序

我的主要目标是JOIN t1.date=t2.date AND t1.driver_id=t2.driver_id获取driver_id

问题:历史记录表不是每天跟踪分配,而是使用间隔。如果我在一个月前指派司机发送,它将只有一个条目。如果我今天更改该驱动程序的调度,它将在今天添加另一个条目,同样,如果我多次更改调度,它将在同一天添加多个条目,具有不同的时间戳,我需要在两个分配之间匹配交付时间

问题:虽然内部联接不是问题,但我无法找到满足上述逻辑的解决方案。

SELECT 
 t1.date, t1.driver_id, t2.dispatch_id
FROM 
 DELIVERY as t1
INNER JOIN 
 DRIVER_DISPATCH_HISTORY as t2
  ON t1.date=t2.date 
   AND 
     t1.driver_id=t2.driver_id

假设driver_id和dispatch_id匹配,并且可能有很多交付

enter image description here

2 个答案:

答案 0 :(得分:2)

您想要的是最高发货日期低于交货日期。编写一个查找此日期的子查询,然后将其与调度历史记录表连接以获取调度ID。

SELECT x.driver_id, x.date, y.dispatch_id
FROM (
    SELECT t1.driver_id, MAX(t2.date) AS dispatch_date, t1.date
    FROM delivery AS t1
    JOIN driver_dispatch_history AS t2 
    ON t1.driver_id = t2.driver_id AND t1.date > t2.date
    GROUP BY t1.driver_id, t1.date) AS x
JOIN driver_dispatch_history AS y
ON x.driver_id = y.driver_id AND x.dispatch_date = y.date

答案 1 :(得分:1)

试试这个sqlfiddle

SELECT D.date,D.driver_id,H.dispatch_id,
       H.startdate as `Dispatch_Start`,
       H.enddate as `Dispatch_End`
FROM DELIVERY D
INNER JOIN
  (SELECT H2.date as startdate,
      (SELECT MIN(date) 
       FROM DRIVER_DISPATCH_HISTORY H1
       WHERE H1.driver_id = H2.driver_id AND H1.date > H2.date
       ) as enddate,
       driver_id,
       dispatch_id
    FROM DRIVER_DISPATCH_HISTORY H2)H
ON D.driver_id = H.driver_id
AND D.date >= H.startdate
AND (D.date < H.enddate OR H.enddate IS NULL)

首先,您执行内部选择和min(日期)大于日期以查找调度的结束日期。然后,一旦你有表H,就可以很容易地将交货日期与这个H的发货日期范围进行比较。

我只有两行...因为看到你的第一次交付它发生在任何调度发生之前所以它不适合任何日期范围。 row that doesnt fit in any date range

在阅读@ Barmar的逻辑后,我认为它更简单,我写了另一个变体sqlfiddle

SELECT D.date,D.driver_id,
    (SELECT dispatch_id FROM DRIVER_DISPATCH_HISTORY as H
     WHERE H.driver_id = D.driver_id AND H.Date < D.date
     ORDER BY H.date DESC LIMIT 1) as dispatch_id
FROM DELIVERY as D