Mysql 使用时间比较连接两个表 背景

Mysql 使用时间比较连接两个表 背景,mysql,join,database-design,jointable,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列都是DAT

我有两张桌子要合并

表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
类型,因此我可以比较时间

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

问题 我想做的是连接这两个表,这样

1) 对于
表2中的每条记录
,我想分别找到
从id
到id的
坐标x
坐标y

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
-对于'table2'中的每条记录,我取其'time'和'from_id'(或'to_id'),如下所示,

-然后,在“table1”中,查找同一个“id”的最新记录。“移动时间”让我们从一个案例开始,如果2014-06-08 08:01:29123:

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;
它仍然“正常”工作吗

我是否应该将其作为“读者练习”来获取
到_id
的坐标?(提示:另一个连接。)

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;