【发布时间】:2015-09-18 23:10:32
【问题描述】:
设置
我有两个要加入的表。
table1
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
...
table2
communication_time, from_id, to_id
2014-06-08 08:01:29, 123, 321
...
在两个表中,time 列都是DATETIME 类型,所以我可以比较时间。
这两个时间可能不对齐。例如user 123在table1中的移动时间可能不会出现在table2中,如上例所示,反之亦然。
问题
我想做的是加入这两个表,这样
1) 对于table2中的每条记录,我想分别找到from_id和to_id对应的coordinate_x和coordinate_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
如何使用 MySQL 来完成这项任务?
谢谢,
平移
【问题讨论】:
标签: mysql join database-design jointable