通过时间比较加入两个表

时间:2015-07-01 16:53:28

标签: mysql join database-design jointable

设置

我想加入两张桌子。

表1

id, movement_time, coordinate_x, coordinate_y
123, 2014-06-08 08:01:24, 1, 10
123, 2014-06-08 08:01:54, 1, 11
321, 2014-06-08 08:01:30, 99, 2
...

表2

communication_time, from_id, to_id
2014-06-08 08:01:29, 123, 321
...

在这两个表格中,time列都是DATETIME类型,因此我可以比较时间。

这两次可能不一致。例如,user 123table1的移动时间可能不会出现在table2中,如上例所示,反之亦然。

问题

我想要做的是加入这两个表,例如

1)对于table2中的每条记录,我想分别为coordinate_xcoordinate_y找到相应的from_idto_id

2)由于两个时间列不对齐,我很可能找不到精确的时间匹配。所以我使用以下规则:

- For each record in `table2`, I take its `time` and `from_id` (or `to_id`) as given, 

- Then, in `table1`, find the most recent record for the same `id`. The `movement_time` <= `communication_time`

- Attach the coordinates to the `table2` record

如何使用MySQL完成此任务?

谢谢,

1 个答案:

答案 0 :(得分:0)

让我们先来看看2014-06-08 08:01:29,123:

中的一个案例
SELECT t1.coordinate_x, t1.coordinate_y
    FROM table1 AS t1
    WHERE t1.movement_time <= '2014-06-08 08:01:29'
      AND t1.id = 123
    ORDER BY t1.movement_time DESC
    LIMIT 1;

这将受益于INDEX(id, movement_time)

这是否适用于那一个案例?假设确实如此,让我们继续实际使用table2:

SELECT t2.communication_time,
       t1a.coordinate_x AS from_x,
       t1a.coordinate_y AS from_y
    FROM table2 AS t2
    JOIN (
        SELECT t1.coordinate_x, t1.coordinate_y
            FROM table1 AS t1
            WHERE t1.movement_time <= t2.communication_time
              AND t1.id = t2.from_id
            ORDER BY t1.movement_time DESC
            LIMIT 1;
         ) t1a;

它还能正常工作吗?

我应该把它作为“练习给读者”,以获得to_id的坐标吗? (提示:另一个人加入。)